PHP Tutorial - PHP strtotime() Function


The strtotime() function converts strings to a timestamp


PHP strtotime() Function has the following syntax.

int strtotime ( string time [, int now] )


time is the the string time to convert, a second optional parameter that can be a relative timestamp.


Parse about any English textual datetime description into a Unix timestamp


Consider this script:

print strtotime("22nd December 2012"); 
print strtotime("22 Dec. 1979 17:30"); 
print strtotime("2012/12/22"); 

The integer value are the Unix timestamps for the dates we passed into strtotime(). You must use American-style dates (i.e., month, day, year) with strtotime().

If PHP is unable to convert your string into a timestamp, it will return -1.

$mydate = strtotime("Christmas 2012"); 
if ($mydate == -1) { 
   print "Date conversion failed!"; 
} else { 
   print "Date conversion succeeded!"; 

The optional second parameter sets a timestamp to for relative dates. The date string in the first parameter can be relative dates such as "Next Sunday," "20 days," or "7 year ago." In this situation, the second parameter sets the relative times.

For example, this next line of code will print the timestamp for the next Sunday:

print strtotime("Next Sunday"); 

"2 days" after the current timestamp.

print strtotime("2 days", time()); 

subtracts a year from a given timestamp.

print strtotime("1 year ago", 123456789); 

"August 25, 2012, 11:26 p.m." is not a legal string because of the comma.

Example 2

The following code shows how to convert number days to a date.


$futuredate = strtotime("45 days");
echo date("F d, Y", $futuredate);


The code above generates the following result.