3.9. Parsing Dates and Times from Strings
Problem
You need to get a date or time in a string into a format you can use in calculations. For example, you want to convert date expressions such as “last Thursday” into an epoch timestamp.
Solution
The simplest way to parse a date or time string is with
strtotime( )
, which turns a variety of
human-readable date and time strings into epoch timestamps:
$a = strtotime('march 10'); // defaults to the current yearDiscussion
The grammar strtotime( ) uses is both complicated
and comprehensive so the best way to get comfortable with it is to
try out lots of different time expressions. If
you’re curious about its nuts and bolts, check out
ext/standard/parsedate.y
in the PHP source distribution.
The function strtotime( ) understands words about
the current time:
$a = strtotime('now');
print strftime('%c',$a);
$a = strtotime('today');
print strftime('%c',$a);
Mon Aug 12 20:35:10 2002
Mon Aug 12 20:35:10 2002It understands different ways to identify a time and date:
$a = strtotime('5/12/1994');
print strftime('%c',$a);
$a = strtotime('12 may 1994');
print strftime('%c',$a);
Thu May 12 00:00:00 1994
Thu May 12 00:00:00 1994It understands relative times and dates:
$a = strtotime('last thursday'); // On August 12, 2002
print strftime('%c',$a);
$a = strtotime('2001-07-12 2pm + 1 month');
print strftime('%c',$a);
Thu Aug 8 00:00:00 2002
Mon Aug 12 14:00:00 2002It understands time zones. When the following is run from a computer in EDT, it prints out ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access