Basic TutorialsBasic Tutorials
Find out a date that's days from another date
I wrote a simple function and returns the date that's N days from a date you specify. For example, if you provide 2004/03/01 as the input date, it should return 2004/02/29 if you want to find out the date right before 2004/03/01. It uses mktime function.
This function is pretty straight forward and handy. You provide a date with its month, day and year and how many days before or after that date. It will return an array with keys: year, month and day.
Here's an example:
Back
I wrote a simple function and returns the date that's N days from a date you specify. For example, if you provide 2004/03/01 as the input date, it should return 2004/02/29 if you want to find out the date right before 2004/03/01. It uses mktime function.
This function is pretty straight forward and handy. You provide a date with its month, day and year and how many days before or after that date. It will return an array with keys: year, month and day.
<?php
function datefrom($month, $day, $year, $days=1) {
$newtime = mktime(0,0,0,$month, $day+$days, $year);
$returndate[year] = date("Y", $newtime);
$returndate[month] = date("m", $newtime);
$returndate[day] = date("d", $newtime);
return $returndate;
}
?>
If you haven't already notice, you may provide either a positive or negative integer as the fourth parameter. Positive numbers mean the number of days after that day and vice versa.
Here's an example:
<?php
// today's date
$today_year = date("Y");
$today_month = date("m");
$today_day = date("d");
$tomorrowdate = datefrom($today_month, $today_day, $today_year, 1);
echo "Today is $today_year / $today_month / $today_day and tomorrow is
".$tomorrowdate[year]." / ".$tomorrowdate[month]." / ".$tomorrowdate[day]."
";
$yesterdaydate = datefrom($today_month, $today_day, $today_year, -1);
echo "Today is $today_year / $today_month / $today_day and yesterday is
".$yesterdaydate[year]." / ".$yesterdaydate[month]." / ".$yesterdaydate[day]."
";
// a specific date
$year = 2004;
$month = 3;
$day = 1;
$tomorrowdate = datefrom($month, $day, $year, 2);
echo "The date is $year / $month / $day and $days days after it is ".$tomorrowdate[year]."
/ ".$tomorrowdate[month]." / ".$tomorrowdate[day]."
";
$yesterdaydate = datefrom($month, $day, $year, -1);
echo "The date is $year / $month / $day and one day before it is ".$yesterdaydate[year]."
/ ".$yesterdaydate[month]." / ".$yesterdaydate[day]."
";
?>
It should print something like:
Today is 2004 / 06 / 10 and tomorrow is 2004 / 06 / 11 Today is 2004 / 06 / 10 and yesterday is 2004 / 06 / 09 The date is 2004 / 3 / 1 and 2 days after it is 2004 / 03 / 03 The date is 2004 / 3 / 1 and one day before it is 2004 / 02 / 29Click here to download the compelete source. Save the file as datefrom.php and it should run as expected.
Back
Scripts and tutorials © 2003 - 2010 by Ying Zhang. No redistribution without permission!