Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg

PHP : Function Reference : Date and Time Functions : strtotime


Parse about any English textual datetime description into a Unix timestamp (PHP 4, PHP 5)
int strtotime ( string time [, int now] )

Example 463. A strtotime() example

echo strtotime("now"), "\n";
strtotime("10 September 2000"), "\n";
strtotime("+1 day"), "\n";
strtotime("+1 week"), "\n";
strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
strtotime("next Thursday"), "\n";
strtotime("last Monday"), "\n";

Example 464. Checking for failure

= 'Not Good';

// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
"The string ($str) is bogus";
} else {
"$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);

Related Examples ( Source code ) » strtotime

Code Examples / Notes » strtotime


While working on an employee schedule application I noticed an issue with using strtotime('last...').  I ran tests on each weekday for each week within a year and noticed inconsistencies while using:
   date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
Most calculations of the 'last Wednesday' for each week calculated accordingly however I noticed a problem with several dates, one being '04/05/2005' (April 5th 2005).
   date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
The above should have returned '03/30/2005'.  Instead, it returned '03/29/2005'.  I don't understand why the function is returning this value.  Regardless, my solution:
   date('m/d/Y', strtotime('-1 week' ,strtotime('Wednesday', '2005-04-05')))

maxz /*

When you convert date string got by untrusted source (such as If-Modified-Since HTTP Header) don't forget to check if the date string is empty.
<? strtotime('') ?>
returns current timestamp on my php 4.3.8

olav dot morkrid

when using strtotime("wednesday"), you will get different results whether you ask before or after wednesday, since strtotime always looks ahead to the *next* weekday.
strtotime() does not seem to support forms like "this wednesday", "wednesday this week", etc.
the following function addresses this by always returns the same specific weekday (1st argument) within the *same* week as a particular date (2nd argument).
function weekday($day="", $now="") {
 $now = $now ? $now : "now";
 $day = $day ? $day : "now";
 $rel = date("N", strtotime($day)) - date("N");
 $time = strtotime("$rel days", strtotime($now));
 return date("Y-m-d", $time);
example use:
weekday("wednesday"); // returns wednesday of this week
weekday("monday, "-1 week"); // return monday the in previous week
ps! the ? : statements are included because strtotime("") without gives 1 january 1970 rather than the current time which in my opinion would be more intuitive...

tero dot totto

When using multiple negative relative items, the result might be a bit unexpected:
$basedate = strtotime("15 Aug 2005 10:15:00");
$date1 = strtotime("-1 day 2 hours", $basedate);
$date2 = strtotime("-1 day -2 hours", $basedate);
echo date("j M Y H:i:s", $date1);  // 14 Aug 2005 12:15:00
echo date("j M Y H:i:s", $date2);  // 14 Aug 2005 08:15:00
The minus sign has to be added to every relative item, otherwise they are interpreted as positive (increase in time). Other possibility is to use "1 day 2 hours ago".

ian fieggen

To calculate the last Friday in the current month, use strtotime() relative to the first day of next month:
$lastfriday=strtotime("last Friday",mktime(0,0,0,date("n")+1,1));
If the current month is December, this capitalises on the fact that the mktime() function correctly accepts a month value of 13 as meaning January of the next year.


This is an easy way to calculate the number of months between 2 dates (including the months in which the dates are themselves).
$startDate = mktime(0,0,0, 6, 15, 2005);
$stopDate = mktime(0,0,0, 10, 8, 2006);

$nrmonths = ((idate('Y', $stopDate) * 12) + idate('m', $stopDate)) - ((idate('Y', $startDate) * 12) + idate('m', $startDate));
Results in $nrmonths = 16.

alan gruskoff

This function inputs a date sting and outputs an integer that is the internal representation of days that spreadsheets use. Post this value into a cell, then format that cell as a Date.
function conv_to_xls_date($Date) {
// Returns the Excel/Calc internal date integer from either an ISO date YYYY-MM-DD or MM/DD/YYYY formats.
return (int) (25569 + (strtotime("$Date 12:00:00") / 86400));
$Date = "04-07-2007";
$Days =  conv_to_xls_date($Date);
$Days will contain 39179


The pluralization of "minute" or "minutes" for instance does not matter. In case you are dynamically using this function "+1 minutes" or "+2 minute" both do work.

philippe jausions -at-

The PHP 5.1.0 change is a major backward compatibility break.
Now, that the returned value on failure has changed, the correct way to detect problems on all PHP versions is:
if (($time = strtotime($date)) == -1 || $time === false) {
   die 'Invalid date';
[red (derick): note, this is not 100% correct, as in this case 1969-12-31 23:59 will be thrown out as that timestamp is "-1"]


The GNU manual page has moved, the new address is


The following might produce something different than you might expect:
echo date('l, F jS Y', strtotime("third wednesday", strtotime("2006-11-01"))) . "
echo date('l, F jS Y', strtotime("third sunday", strtotime("2006-01-01")));
Wednesday, November 22nd 2006
Sunday, January 22nd 2006
The problem stems from strtotime when the requested day falls on the date passed to strtotime. If you look at your calendar you will see that they should return:
Wednesday, November 15th 2006
Sunday, January 15th 2006
Because the date falls on the day requested it skips that day.


strtotime() reads the timestamp in en_US format if you want to change the date format with this number, you should previously know the format of the date you are trying to parse. Let's say you want to do this :
It will understand the date as 11th of may 2007, and not 5th of november 2007. In this case I would use:
$date = explode("/","05/11/2007");
Much reliable but you must know the date format before. You can use javascript to mask the date field and, if you have a calendar in your page, everything is done.
Thank you.

02-mar-2007 11:29

SQL datetime columns have a much wider range of allowed values than a UNIX timestamp, and therefore this function is not safe to use to convert a SQL datetime column to something usable in PHP4.  Year 9999 is the limit for MySQL, which obviously exceeds the UNIX timestamp's capacity for storage.  Also, dates before 1970 will cause the function to fail (at least in PHP4, don't know about 5+), so for example my boss' birthday of 1969-08-11 returned FALSE from this function.
[red. The function actually supports it since PHP 5.1, but you will need to use the new object oriented methods to use them. F.e:
$date = new DateTime('1969-08-11');
echo $date->format('m d Y');

xurizaemon of the land of gmail

Somewhere between PHP5.0 and PHP5.1.6, strtotime started accepting '.' (period, dot) as well as ':' (colon) as a time separator.
before: "2.30pm" == -1
after: "2.30pm" == 14:30
[red.: This is working since PHP 5.1.0]


Some surprisingly wrong results (php 5.2.0): date and time seem not coherent:
// Date: Default timezone Europe/Berlin   (which is CET)
// date.timezone no value
$basedate = strtotime("31 Dec 2007 23:59:59");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG
$basedate = strtotime("31 Dec 2007 23:59:59 CET");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG
$basedate = strtotime("31 Dec 2007 23:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:59:59 CORRECT
$basedate = strtotime("31 Dec 2007 22:59:59 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 23:59:59 WRONG AGAIN
$basedate = strtotime("31 Dec 2007 00:00:00 GMT");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 01:00:00 CORRECT
$basedate = strtotime("31 Dec 2007 00:00:00 CET");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:00:00 WRONG AGAIN
$basedate = strtotime("31 Dec 2007 00:00:01");
$date1 = strtotime("-3 months", $basedate);
echo date("j M Y H:i:s", $date1);  // 1 Oct 2007 00:00:01 WRONG AGAIN


relative dates..
echo date('d F Y', strtotime('last monday', strtotime('15 July 2005'))); // 11th
echo "
echo date('d F Y', strtotime('this monday', strtotime('15 July 2005'))); // 18th
echo "
echo date('d F Y', strtotime('next monday', strtotime('15 July 2005'))); // 25th


Regarding the previous post on strtotime() being used to convert mysql datetime strings, I agree that this is not widely realized.
Part of the reason for this is that it is only a relatively recent addition. Prior to PHP 5.0, though it might have been an earlier version, strtotime() would return -1 on a mysql datetime string.
If you're on a server that doesn't have a recent PHP version test your result before assuming this one works.


Regarding the "NET" thing, it's probably parsing it as a time-zone.  If you give strtotime any timezone string (like PST, EDT, etc.) it will return the time in that time-zone.
In any case, you shouldn't use strtotime to validate dates.  It can and will give incorrect results.  As just one shining example:
Date: 05/01/2007
To most Americans, that's May 1st, 2007.  To most Europeans, that's January 5th, 2007.  A site that needs to serve people around the globe cannot use strtotime to validate or even interpret dates.
The only correct way to parse a date is to mandate a format and check for that specific format (preg_match will make your life easy) or to use separate form fields for each component (which is basically the same thing as mandating a format).


Previous comments regarding dates prior to 1970 may be out of date.
In PHP 5.2.3 on Linux:
$timestamp = strtotime( "February 26, 1946" );
print date( 'Y-m-d', $timestamp );
Output is "1946-02-26", as expected.


PHP 5.1.0 and above might overcome the limitation of parsing dates earlier than 1970, but they still do it at a much slower pace (About 0.5 seconds). Just a note for anyone trying to use this function for this purpose.


One more difference between php 4 and 5 (don't know when they changed this) but the string 15 EST 5/12/2007 parses fine with strtotime in php 4, but returns the 1969 date in php 5.  You need to add :00 to make it 15:00 so php can tell those are hours.  There's no change in php 4 when you do this.


One behavior to be aware of is that if you have "/" in the date then strtotime will believe the last number is the year, while if you use a "-" then the first number is the year.
12/4/03 will be evaluated to the same time as 03-12-4.
This is in the gnu documentation linked to in the article.  I confirmed the behavior with strtotime and getdate.
Steve Holland


Note that strtotime('next month') will return 2 months from now, which may not be what you expect. strtotime('month') will do 1 month.

16-dec-2005 01:31

Note that by default strtotime( ) considers the string time like a local time.
If your input string time is GMT/UTC do :
   $date = '2005-12-25 00:56:27 GMT' ; // Note the timezone specification
   $time = strtotime($date) ;
   echo date('d/m/Y H:i:s', $time) ; // $date will be correctly localized
   // « 25/12/2005 01:56:27 » for France

rob allen

Note strtotime() in PHP 4 does not support fractional seconds.
See especially if you happen to swap to ODBC for MS SQL Server and wonder what's happened!


Note about strtotime() when trying to figure out the NEXT month...
strtotime('+1 months'), strtotime('next month'), and strtotime('month') all work fine in MOST circumstances...
But if you're on May 31 and try any of the above, you will find that 'next month' from May 31 is calculated as July instead of June....


Maybe it saves others from troubles:
if you create a date (i.e. a certain day, like 30.03.2005, for a calendar for example) for which you do not consider the time, when using mktime be sure to set the time of the day to noon:
   $iTimeStamp = mktime(12, 0, 0, $iMonth, $iDay, $iYear);
   // For example
   strtotime('-1 month', $iTimeStamp);
will cause troubles when calculating the relative time. It often is one day or even one month off... After I set the time to noon "strtotime" calculates as expected.


Just a note ... there cannot be spaces between the + and the amount you want to add.
strtotime("{$myDate} -1 months") is correct.
strtotime("{$myDate} - 1 months") is not.
Caused me a headache ...


It looks like in the latest release of PHP 5.1, when passing to strtotime this string "12/32/2005", it will now return the date "12/31/1969". (The previous versions would return "1/1/2006".)


If you strtotime the epoch (Jan 1 1970 00:00:00) you will usually get a value, rather than the expected 0. So for example, if you were to try to use the epoch to calculate the difference in times (strtotime(Jan 1 1970 21:00:00)-strtotime(Jan 1 1970 20:00:00) for example) You get a value that depends strongly upon your timezone. If you are in EST for example, the epoch is actually shifted -5 to YOUR epoch is Jan 1 1970 19:00:00) In order to get the offset, simply use the following call to report the number of seconds you are away from the unix epoch. $offset=strtotime("1970-01-01 00:00:00"); Additionally, you can append GMT at the end of your strtotime calls so save yourself the trouble of converting relative to timezone.


I'm posting these here as I believe these to be design changes, not bugs.
For those upgrading from PHP 4 to PHP 5 there are a number of things that are different about strtotime that I have NOT seen documented elsewhere, or at least not as clearly. I confirmed these with two separate fresh installations of PHP 4.4.1 and PHP 5.1.1.
1) Given that today is Tuesday: PHP4 "next tuesday" will return today. PHP5 "next tuesday" will actually return next tuesday as in "today +1week". Note that behavior has NOT changed for "last" and "this". For the string "last tuesday" both PHP4 and PHP5 would return "today -1week".  For the string "this tuesday" both PHP4 and PHP5 would return "today".
2) You cannot include a space immediately following a + or - in PHP 5. In PHP4 the string "today + 1 week" works great. in PHP5 the string must be "today +1 week" to correctly parse.
3) (Partially noted in changelog.) If you pass php4 a string that is a mess ("asdf1234") it will return -1. If you in turn pass this to date() you'll get a warning like: Windows does not support dates prior to midnight. This is pretty useful for catching errors in your scripts. In PHP 5 strtotime will return FALSE which causes date() to return 12/31/69. Note that this is true of strings that might appear right such as "two weeks".
4) (Partially noted in changelog.) If you pass php4 an empty string it will error out with a "Notice: strtotime(): Called with empty time parameter". PHP5 will give no notice and return the current date stamp. (A much preferred behavior IMO.)
5) Some uppercase and mixed-case strings no longer parse correctly. In php4 "Yesterday" would parse correctly. In php5 "Yesterday" will return the infamous 1969 date. This is also true of Tomorrow and Today. [Red. This has been fixed in PHP already]
6. The keyword "previous" is supported in PHP5. (Finally!)
Good luck with your upgrades. :)


I was having trouble parsing Apache log files that consisted of a time entry (denoted by %t for Apache configuration). An example Apache-date looks like: [21/Dec/2003:00:52:39 -0500]
Apache claims this to be a 'standard english format' time. strtotime() feels otherwise.
I came up with this function to assist in parsing this peculiar format.
function from_apachedate($date)
       list($d, $M, $y, $h, $m, $s, $z) = sscanf($date, "[%2d/%3s/%4d:%2d:%2d:%2d %5s]");
       return strtotime("$d $M $y $h:$m:$s $z");
Hope it helps anyone else seeking such a conversion.

05-apr-2005 07:45

I ran into the same problem with "last" as gabrielu at hotmail dot com (05-Apr-2005 10:45) when using strtotime() with getdate(). My only guess is that it has to do with daylight savings time as it seemed to be ok for most dates except those near the first Sunday in April and last Sunday in October.
I used strftime() with strtotime() and that gave me the result I was looking for.


I neglected to include the solution in my last post for using strtotime() with date-time data stored in GMT.  Append the string "GMT" to all of your datetimes pulled from MySQL or other database that store date-times in the format "yyyy-mm-dd hh:ii:ss" just prior to converting them to a unix timestamp with strtotime().  This will ensure you get a valid GMT result for times during daylight savings.
$date_time1 = strtotime("2004-04-04 02:00:00"); // returns bad value -1 due to DST
$date_time2 = strtotime("2004-04-04 02:00:00 GMT"); // works great!

jacques dot malan

I have had some inconsistancies that was not immediately evident and suggested that strtotime treated my date formats in different ways.
I had trouble with the date format: d/m/Y
I eliminated the inconsistancies by changing the date format to one where (i guess) php does not try and guess the right format. In my case I changed it to the format (d-M-Y) in which case it worked.
Example when trying to find a person's age where:
//$date in format (d/m/Y) was inconsistant but fixed when in format (d-M-Y), e.g. (01-January-2001)
$age = (time() - strtotime($date))/(60*60*24*360);


I am thinking this function may have a bug in it. Can anyone explain why strtotime when parsing two RSS-2 newfeeds with ISO-2822 timestamps for the pubDate can give true in the first case and false in the second case?
Wed, 22 Aug 2007 21:23:51 -0500 (This works)
Mon, 27 Aug 2007 12:47:06 +0000 (This returns false)
I am using PHP 5.1.2.


Here's a quick one-line function you can use to get the time difference for relative times. But default, if you put in a relative time (like "1 minute"), you get that relative to the current time. Using this function will give you just the time difference in seconds:
<?php function relative_time( $input ) { return strtotime($input) - time(); } ?>
For example "1 minute" will return 60, while "30 seconds ago" will return -30
Valid relative time formats can be found at


Here the workaround to the bug of strtotime() found in my previous comment on finding the exact date and time of "3 months ago of last second of this year", using mktime() properties on dates instead of strtotime(), and which seems to give correct results:
// check for equivalency
$basedate = strtotime("31 Dec 2007 23:59:59");
$timedate = mktime( 23, 59, 59, 1, 0, 2008 );
echo "$basedate $timedate "; // 1199141999 1199141999 : SO THEY ARE EQUIVALENT
// workaround, as mktime knows to handle properly offseted dates:
$date1 = mktime( 23, 59, 59, 1 - 3, 0, 2008 );
echo date("j M Y H:i:s", $date1);  // 30 Sep 2007 23:59:59 CORRECT


Be warned that strtotime() tries to "guess what you meant" and will successfully parse dates that would otherwise be considered invalid:
$ts = strtotime('1999-11-40');
echo date('Y-m-d', $ts);
// outputs: 1999-12-10
It is my understanding (I have not verified) that the lexer for strtotime() has been rewritten for PHP5, so these semantics may only apply for PHP4 and below.

15-oct-2006 10:50

Be careful, strtotime("+1 month", strtotime("2006-05-31"));
returns 2006-07-01!


Another inconsistency between versions:
print date('Y-m-d H:i:s', strtotime('today')) . "\n";
print date('Y-m-d H:i:s', strtotime('now')) . "\n";
In PHP 4.4.6, "today" and "now" are identical, meaning the current timestamp.
In PHP 5.1.4, "today" means midnight today, and "now" means the current timestamp.


After a slight moment of frustration, and finding that I'm not the only one with this problem (see - it's a known bug) I decided to write a short workaround for dealing with the 00 hour problem.
The problem only seems to occur when inputting strings such as '08/20/2004 0047' and NOT '08/20/2004 00:47'.  Hence, my fix:
$your_value ( preg_replace ('#^(\d+/\d+/?\d{2,4} )(00)(\d{2})$#', '$1$2:$3', $your_value() ));


a simple way to find the first day of a month
echo date('l, F jS Y', strtotime("first day", strtotime("August 0 2007")));
Wednesday, August 1st 200


A major difference in behavior between PHP4x and newer 5.x versions is the handling of "illegal" dates: With PHP4, strtotime("2007/07/55") gave a valid result that could be used for further calculations.
This does not work anymore at PHP5.xx (here: 5.2.1), instead something like strtotime("$dayoffset_relative_to_today days","2007/07/19") is to be used.


A hint not to misunderstand the second parameter:
The parameter "[, int now]" is only used for strings which describe a time difference to another timestamp.
It is not possible to use strtotime() to calculate a time difference by passing an absolute time string, and another timestamp to compare to!
$day_before = strtotime("+1 day", $timestamp);
# result is a timestamp relative to another
$diff = strtotime("2007-01-15 11:40:00", time());
# result it the timestamp for the date in the string;
# because the string contains an absolute date and time,
# the second parameter is ignored!
# instead, use:
$diff = time() - strtotime("2007-01-15 11:40:00");


Since the first day of a month is always the first (unless I missed something in History), you could save yourself some overhead from the second strtotime() by forcing the day manually:
echo date('l, F jS Y', strtotime('August 1 2007'));
// Outputs "Wednesday, August 1st 2007"
While it's a relatively minor performance difference in a small script, it would be compounded significantly in larger applications or loops.

mr obvious

@ nick at fortawesome dot co dot uk
regarding 'month' vs 'next month'
Not sure what version of PHP you found those results on, however with PHP 4.4.0,
$time1=strtotime('next month');
produce the exact same result.

Change Language

Follow Navioo On Twitter
eXTReMe Tracker