I find I often need to convert either a UNIX timestamp (e.g. 1337396586) or an ISO/SQL date (e.g. 2012-05-19) 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 (1337396586)iso: ISO date (2012-05-19)dmy: numeric day-month-year format (19/05/2012)mdy: numeric month-day-year format (05/19/2012)short: short format (19 May 2012)long: long format (19th May 2012)http: "Last-Modified" HTTP header format (Sat, 19 May 2012 03:03:06 GMT)
A couple of examples:
ts2dmy(1337396586)returns19/05/2012.iso2short("2012-05-19")returns19 May 2012.
Here are the functions for converting from UNIX timestamps:
<?php // ts2iso: ISO format (2012-05-19) function ts2iso ($ts) { return date("Y-m-d", $ts); } // ts2dmy: numeric day-month-year format (19/05/2012) function ts2dmy ($ts) { return date("d/m/Y", $ts); } // ts2mdy: numeric day-month-year format (05/19/2012) function ts2mdy ($ts) { return date("m/d/Y", $ts); } // ts2short: short format (19 May 2012) function ts2short ($ts) { return date("j M Y", $ts); } // ts2long: long format (19th May 2012) function ts2long ($ts) { return date("jS F Y", $ts); } // ts2http: HTTP "Last-Modified" format (Sat, 19 May 2012 03:03:06 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 (1337425200) 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 (19/05/2012) function iso2dmy ($iso) { return ts2dmy(iso2ts($iso)); } // iso2mdy: numeric day-month-year format (05/19/2012) function iso2mdy ($iso) { return ts2mdy(iso2ts($iso)); } // iso2short: short format (19 May 2012) function iso2short ($iso) { return ts2short(iso2ts($iso)); } // iso2long: long format (19th May 2012) function iso2long ($iso) { return ts2long(iso2ts($iso)); } // iso2http: HTTP "Last-Modified" format (Sat, 19 May 2012 03:03:06 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.