strtotime()
function?The strtotime()
function is a built-in function in PHP that converts a date or time-related strings into real date/time
objects. This function is so powerful that it can parse virtually any datetime related English text to Unix timestamp.
The Unix timestamp is the number of seconds since January 1, 1970, 00:00:00 UTC.
This function will format a time string into a Unix timestamp relative to the provided baseTimeStamp
argument.
strtotime($datetime,$baseTimeStamp)
dateTime
: This parameter is any valid English string in the date/time
format.baseTimeStamp
This parameter will be used as the timestamp to calculate the relative date. This parameter can be omitted and, if omitted, will be assumed to be the current time.Different English time/date strings are parsed and converted to Unix timestamp they represent using the strtotime()
function in the code below.
<?phpecho(strtotime("now") . "<br>");echo(strtotime("9 October 2021") . "<br>");echo(strtotime("+2 hours") . "<br>");echo(strtotime("+4 week") . "<br>");echo(strtotime("+5 week 10 days 5 hours 30 seconds") . "<br>");echo(strtotime("next Tuesday") . "<br>");echo(strtotime("last Friday")). "<br>";echo(strtotime("tomorrow"));?>
It may be challenging to make sense of the output above. The code below presents the formatted date strings in a more understandable manner.
<?php//declare a datetime string$str = 'tomorrow';$timestamp = strtotime($str);// This will check for wrong datetime stringif ($timestamp === false) {echo "The string ($str) is vague";} else {echo "$str is: " . date('l dS \o\f F Y h:i:s A', $timestamp);}?>