PHP strtotime() function is used to convert an English textual date-time description to a UNIX timestamp(the number of seconds since January 1 1970 00:00:00 UTC).
Syntax
strtotime($time, $now);
Parameters
- $time(required): It specifies a date/time string.
- $now(optional): It specifies the timestamp used to calculate the returned value. It is an optional parameter. Since the time/date is not static, the output will vary.
Return value
It returns a Unix timestamp on success, and false on failure.
Visual Representation
Example 1: How to Use strtotime() Function
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 1993"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+2 week"), "\n";
echo strtotime("+3 week 2 days 4 hours 11 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
Output
1699776875
747619200
1699863275
1700986475
1701778486
1700092800
1699228800
Example 2: Convert English text to a date
<?php
$textDate = "19th february 2004";
echo strtotime($textDate), "\n";
echo date("Y-m-d", strtotime($textDate))."\n";
Output
1077148800
2004-02-19
Example 3: PHP strtotime() doesn’t work with dd/mm/YYYY format
When working on the project, you often come across a date format that looks like dd/mm/YYYY.
Suppose you have a date in dd/mm/YYYY format; how can you convert it to YYYY-mm-dd using the strtotime() function? But when you apply the strtotime() function to that format, then it won’t work. Again, it works only with the mm/dd/YYYY format.
Dates in the mm/dd/YYY or dd-mm-YYYY formats are illustrated by examining the separator between the different components. If the separator is a slash (/), then the American mm/dd/YYYY is assumed. In contrast, if the separator is a dash (-) or a dot (.), then the European dd-mm-YYYY format is assumed.
$date = '12/11/2023';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));
Output
2023-11-12
That’s it.
Bob
Tell us what it returns if the date is INVALID!!!!