| ¶ Code - datetimestamp | Monday, Feb 2, 2009 2:28 pm |
This is a PHP function that records a date/timestamp as a human-readable long number and includes functions that can easily display it in any of a number of formats. I wrote this because I wasn't satisfied with PHP's built-in timestamp function that displays the number of seconds since the Unix Epoch. This large number is not only meaningless at first glance, it also changes in length every 10x seconds. This is unsuitable for functions that need the timestamp to be readable by character placement, and also for simple databases where it's nice to have a timestamp that's easy to look at and understand.
/*
PHP function to record a datetimestamp as a human-readable
long number and read it back in a different format.
Variables:
$year 4 digit year (1900-3000)
$mon 2 digit month (01-12)
$day 2 digit day (01-31)
$hour 2 digit hour (00-23)
$min 2 digit hour (00-59)
$sec 2 digit second (00-59)
*/
// Initialize
$datetimestamp = date('YmdHis',time());
$year = substr($datetimestamp,0,4);
$mon = substr($datetimestamp,4,2);
$day = substr($datetimestamp,6,2);
$hour = substr($datetimestamp,8,2);
$min = substr($datetimestamp,10,2);
$sec = substr($datetimestamp,12,2);
$datetime = mktime($hour,$min,$sec,$mon,$day,$year);
// Debug
echo "datetimestamp: ".$datetimestamp."<br />";
echo "year: ".$year."<br />";
echo "mon: ".$mon."<br />";
echo "day: ".$day."<br />";
echo "hour: ".$hour."<br />";
echo "min: ".$min."<br />";
echo "sec: ".$sec."<br />";
// Examples
$longdatetime = date("l, F d, Y g:i:s a",$datetime);
echo "longdatetime: ".$longdatetime."<br />";
$shortdatetime = date("D M d",$datetime);
echo "shortdatetime: ".$shortdatetime."<br />";
$numdatetime = date("Y-m-d H:i:s",$datetime);
echo "numdatetime: ".$numdatetime."<br />";
?>
Linked: Code