I find I often need to convert either a UNIX timestamp (e.g. 1328465544) or an ISO/SQL date (e.g. 2012-02-05) into something else; here is the collection of functions I use.
They are divided into two groups: the functions in one are for timestamps and are called ts2something(); the functions in the other are for ISO dates and are called iso2something().
The something bit of the name can be replaced with any of the following:
ts: UNIX timestamp (1328465544)iso: ISO date (2012-02-05)dmy: numeric day-month-year format (05/02/2012)mdy: numeric month-day-year format (02/05/2012)short: short format (5 Feb 2012)long: long format (5th February 2012)http: "Last-Modified" HTTP header format (Sun, 05 Feb 2012 18:12:24 GMT)
A couple of examples:
ts2dmy(1328465544)returns05/02/2012.iso2short("2012-02-05")returns5 Feb 2012.
Here are the functions for converting from UNIX timestamps:
<?php // ts2iso: ISO format (2012-02-05) function ts2iso ($ts) { return date("Y-m-d", $ts); } // ts2dmy: numeric day-month-year format (05/02/2012) function ts2dmy ($ts) { return date("d/m/Y", $ts); } // ts2mdy: numeric day-month-year format (02/05/2012) function ts2mdy ($ts) { return date("m/d/Y", $ts); } // ts2short: short format (5 Feb 2012) function ts2short ($ts) { return date("j M Y", $ts); } // ts2long: long format (5th February 2012) function ts2long ($ts) { return date("jS F Y", $ts); } // ts2http: HTTP "Last-Modified" format (Sun, 05 Feb 2012 18:12:24 GMT) function ts2http ($ts) { return gmdate("D, d M Y H:i:s", $ts). " GMT"; } ?>
And here are their equivalents for ISO dates:
<?php // iso2ts: UNIX timestamp format (1328443200) function iso2ts ($iso, $hour=12, $min=0, $sec=0) { $d = substr($iso, 8, 2); $m = substr($iso, 5, 2); $y = substr($iso, 0, 4); return mktime($hour, $min, $sec, $m, $d, $y); } // iso2dmy: numeric day-month-year format (05/02/2012) function iso2dmy ($iso) { return ts2dmy(iso2ts($iso)); } // iso2mdy: numeric day-month-year format (02/05/2012) function iso2mdy ($iso) { return ts2mdy(iso2ts($iso)); } // iso2short: short format (5 Feb 2012) function iso2short ($iso) { return ts2short(iso2ts($iso)); } // iso2long: long format (5th February 2012) function iso2long ($iso) { return ts2long(iso2ts($iso)); } // iso2http: HTTP "Last-Modified" format (Sun, 05 Feb 2012 18:12:24 GMT) function iso2http ($iso, $hour=12, $min=0, $sec=0) { return gmdate("D, d M Y H:i:s", iso2ts($iso, $hour, $min, $sec)). " GMT"; } ?>
Note: iso2ts() and iso2http() have three optional parameters which you can use to specify the hour, minute and second for the output. If you ignore them, you'll get the default of 12 noon local time.
Questions? Suggestions for improvement? Feel free to get in touch.