Jon Haworth

PHP: Date convertors


I find myself storing either ISO format dates or UNIX timestamps in my databases, and generally end up doing everything in the code with timestamps. These are the functions I use to convert the two to each other and to format them for output.

I have my own preferred "long" and "short" date formats which I use for most output that users see (you might want to change these), and standard "dd/mm/yyyy" and "mm/dd/yyyy" formats in case they're handy.

Two code-related notes: firstly, the default for the iso2ts() function is 3am, to allow for consistency of results on days when the clocks change. Secondly, I haven't included any error checking in these functions, so it's your problem to make sure whatever you pass into them is in the right format :-)


function iso2ts ($iso, $hour=3, $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);
}

function iso2dmy   ($iso) { return ts2dmy(iso2ts($iso));   }
function iso2mdy   ($iso) { return ts2mdy(iso2ts($iso));   }
function iso2short ($iso) { return ts2short(iso2ts($iso)); }
function iso2long  ($iso) { return ts2long(iso2ts($iso));  }

function ts2iso    ($ts) { return date("Y-M-d", $ts);  } 
function ts2dmy    ($ts) { return date("d/m/Y", $ts);  }
function ts2mdy    ($ts) { return date("m/d/Y", $ts);  } 
function ts2short  ($ts) { return date("d M y", $ts);  }
function ts2long   ($ts) { return date("jS F Y", $ts); }
		

More PHP?

Photo