Recipe 3.2. Converting Time and Date Parts to an Epoch Timestamp


3.2.1. Problem

You want to know what epoch timestamp corresponds to a set of time and date parts.

3.2.2. Solution

Use mktime( ) if your time and date parts are in the local time zone, as shown in Example 3-7.

Getting a specific epoch timestamp

<?php // 7:45:03 PM on March 10, 1975, local time $then = mktime(19,45,3,3,10,1975); ?>

Use gmmktime( ) , as in Example 3-8, if your time and date parts are in GMT.

Getting a specific GMT-based epoch timestamp

<?php // 7:45:03 PM on March 10, 1975, in GMT $then = gmmktime(19,45,3,3,10,1975); ?>

3.2.3. Discussion

The functions mktime( ) and gmmktime( ) each take a date and time's parts (hour, minute, second, month, day, year) and return the appropriate Unix epoch timestamp. The components are treated as local time by mktime( ), while gmmktime( ) treats them as a date and time in UTC. These functions return sensible results only for times within the epoch. Most systems store epoch timestamps in a 32-bit signed integer, so "within the epoch" means between 8:45:51 P.M. December 13, 1901 UTC and 3:14:07 A.M. January 19, 2038 UTC.

In Example 3-9, $stamp_future is set to the epoch timestamp for 3:25 P.M. on June 4, 2012. The epoch timestamp can be fed back to strftime( ) to produce a formatted time string.

Working with epoch timestamps

<?php $stamp_future = mktime(15,25,0,6,4,2012); print $stamp_future; print strftime('%c',$stamp_future); ?>

Example 3-9 prints:

1338837900 Mon Jun 4 15:25:00 2012

Because the calls to mktime( ) in Example 3-9 were made on a computer set to EDT (which is four hours behind GMT), using gmmktime( ) instead produces epoch timestamps that are 14,400 seconds (four hours) smaller, as shown in Example 3-10.

Epoch timestamps and gmmktime( )

<?php $stamp_future = gmmktime(15,25,0,6,4,2012); print $stamp_future; print strftime('%c',$stamp_future); 

Example 3-10 prints:

1338823500 Mon Jun 4 11:25:00 2012

Feeding a gmmktime( )-generated epoch timestamp back to strftime( ) produces formatted time strings that are also four hours earlier.

In versions of PHP before 5.1.0, mktime( ) and gmmktime( ) could accept an optional boolean seventh argument indicating a DST flag (1 if DST is being observed, 0 if not). In PHP 5.1.0 and up, whether daylight savings time is being observed is controlled by the currently active default time zone, set with date_default_timezone_set( ) .

3.2.4. See Also

Recipe 3.3 for how to convert an epoch timestamp back to time and date parts; documentation on mktime( ) at http://www.php.net/mktime and gmmktime( ) at http://www.php.net/gmmktime, and on date_default_timezone_set( ) at http://www.php.net/date_default_timezone_set.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net