PHP Dates and Times
Converting an Epoch Timestamp to Time and Date Parts
Problem
You want the set of time and date parts that corresponds to a particular epoch timestamp.Solution
Pass an epoch timestamp to getdate(): $time_parts = getdate(163727100);.Discussion
The time parts returned by getdate() are detailed in Table. These time parts are relative to whatever PHP’s time zone is set to. If you want time parts relative to another time zone, you can change PHP’s time zone with date_default_timezone_set(), and then change it back after your call to getdate(). You could also create a DateTime object, set it to a specific time zone, then retrieve the time and date parts you need with that object’s format() method:$when = new DateTime("@163727100");
$when->setTimezone(new DateTimeZone('America/Los_Angeles'));
$parts = explode('/', $when->format('Y/m/d/H/i/s'));
// Year, month, day, hour, minute, second
// $parts is array('1975', '03','10', '16','45', '00'))
The @ character tells DateTime that the rest of the argument to the constructor is an epoch timestamp. When specifying a timestamp as the initial value, DateTime ignores any time zone also passed to the constructor, so setting that requires an additional call to setTimezone(). Once that’s done, format() can generate any parts you need.
No comments:
Post a Comment