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 year
Discussion
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 2002
It 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 1994
It 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 2002
It understands time zones. When the following is run from a computer in EDT, it prints out ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.