PHP: Calculating past and future datesThe strtotime function in PHP is incredibly powerful but very much underutilised - mainly because some aspects can be a bit confusing and people are more confident 'doing things the hard way'. The strtotime function doesn't just convert date strings to timestamp values but also has its own 'language' to let you specify just about any date or time you want. Calculating dates for past and future daysThe easiest and most common calculations are based on seconds, minutes, hours and days. Months and years are also valid input but not always useful in calculations as they're not all of equal length because of the way our calendar works. Shown below are the results of various strings passed to strtotime and converted to date strings. For example: echo date('l jS F (Y-m-d)', strtotime('-3 days'));
As always there are often different ways to achieve the same result. In the list above you can see that '3 days ago' is equivalent to '-3 days'. Also 'yesterday' is the same as '-1 days' or '1 day ago'. The 's' on the end of 'days', 'years' or other measurements can be left off if you want. The 'now' and 'today' input values in the list above are superfluous as if we leave off the second paramater of the date function it will default to the current time anyway. Working with days of the weekSometimes we work with days of the week and need to know the last/next occurrence of, for example, a Saturday:
In the list above we can see that 'Saturday', 'this Saturday' and 'first Saturday' are all equivalent. The 'this' and 'first' keywords are only used to improve readability. Now it gets a bit complicated to explain. The following appears on the PHP website: In PHP 5 up to 5.0.2, "now" and other relative times are wrongly computed from today's midnight. It differs from other versions where it is correctly computed from current time. In addition, they've introduced 'second' as in 'second Saturday' and seem to have changed the meaning of 'next' to mean the same as 'first'. Finally, the return value on failure is now FALSE instead of -1. This last change is the most likely to cause problems in legacy applications. The table below shows how the output has changed:
Using offsets to get the right dayAnother problem is when you want to find the previous or next occurence of a certain day of the week. For example, today being a Saturday we can run the following:
You can see in the table above that, while 'next Saturday' returns the same result, the 'first', 'second', 'third', ... modifiers have all changed in meaning - thankfully to a more logical state. You may notice also that this only occurs when you're calculating from the current day and not in the previous examples (unless today is Saturday). Whenever you do calculations based on days you should test as many possibilities as possible: Does it work today? yesterday? tomorrow? and so on. Sometimes you want to find the last occurence of a day before today, or before yesterday or before 2 days ago. The following examples show the syntax you can use for this:
Now that you understand the inner workings of strtotime you should be able to drastically reduce the amount of code required to calculate past and future dates. Checking if a date is in the Past or FutureThe strtotime function returns an integer value so it's a simple matter to see if a date is in the past or in the future. if(strtotime(dateString) > time()) {
# date is in the future
}
if(strtotime(dateString) < time()) {
# date is in the past
}
if(strtotime(dateString) == time()) {
# date is right now
}
Note: time() is equivalent to date('U') and returns the current timestamp to the nearest second. You might want to replace time() with strtotime('0:00') if you want to compare a date string to the current date rather than the current date and time. ReferencesSend Feedback |
||||||||
|
© Copyright 2012 Chirp Internet
- Page Last Modified: 30 March 2011
|
||||||||
User Comments and Notes
Tony D 11 September, 2007
The tutorial is really helpful, but some code would be nice. I need a function to tell me if some MYSQL date is between now and the upcoming Sunday. Any help?
In MySQL you can convert a date to a UNIX timestamp using the UNIX_TIMESTAMP function. That value can then be checked to see whether it falls between time() and strtotime('this Sunday').
Renee 31 March, 2008
This tutorial has helped me with several projects. Thank you!
patrick 13 October, 2008
Thanks. I was prepared to insert several lines of code to change current date to (+ 7 days).. with your suggestions I've made it in a few characters. Well done!
Ian 6 September, 2009
What if I wanted to determine what day of the week, month the 100th day would be if the user inputed a specific starting date?
Something like this will work where YYYY-MM-DD is your starting date:
date('l jS F Y', strtotime('YYYY-MM-DD +100 days'));Philippe 17 September, 2009
Hello, I am looking to find a way to get the first tuesday of any month. I can't seem to figure it out. do you have any idea?
Use the first of the month, which is simple, and then 'Tuesday'.
strtotime('1 September 2010 Tuesday');Penny Auction Script 8 November, 2010
Cool i used it and it work in first go. Thanks
Victor 31 January, 2011
Today is 31 January 2011.
I try to calculate the next month:
date('F',strtotime('+1 months'));
The answer is: March ???
A common problem. According to PHP, 1 month after 31 January 2011 will be 31 February. In our calendar that actually means 3 March. To avoid this you need to calculate the offset from the start of the current month.
Catherine Lea 17 February, 2011
If we have an event that is always the second Saturday in July, how many numbers will we need for banners? e.g. 2009 11th, 2010 10th, 2011 9th, which other numbers will we need?
<?PHPfor($year=2000; $year <= 2050; $year++) {
echo date('l jS F, Y', strtotime("{$year}-07-01 second Saturday")) . "<br>";
}
?>
Ian 22 February, 2011
After looking at some other methods of doing this when I came to yours I thought this couldn't possibly work...but it did! Simple script works flawlessy, thanks man will be using it in my projects!
Richard Cummings 6 March, 2011
I have just been doing some work with dates today and this page has helped me immensely. Thank you
James Philips 29 March, 2011
Bug?
I have the code:
$tUnixTime= strtotime('second sunday may 2011');
echo $sGMTMySqlString = gmdate("Y-m-d H:i:s", $tUnixTime);
The real answer should be:
2011-05-08 04:00:00
The program is giving:
2011-05-15 04:00:00
what I am doing bad?
The following strtotime examples should explain it:
In short, 'may 2011' is already a Sunday, so the counting starts from there. What you could use instead is '30 april 2011 second Sunday' to get the value you're after.
Richard Cummings 31 August, 2011
I may have commented here before but I keep coming back to this page when I am searching for PHP date information and it is always right on the money with the syntax I need. Thx
Sumit Mathur 7 October, 2011
Really a great Post! Thanks. It helped me in handling such kind of date and day issues!

shalin nathan 1 December, 2011
how to calcutate the day of the future year..and what is the main logic behind this calculation and how does it flow in that method
as if the day i want to calcute is 26 feb 2028 and today is 1 dec 2011 so what will be the day on 26 feb 2028..
It's really not as complicated as you think:

$dayofweek = date('l', strtotime('26 feb 2028')); // Saturday