Archive for September, 2008

Change date format in PHP

When coding in PHP & MySQL dealing with date is a huge headache if you are not prepared for it. As MySQL dates are in the format ‘yyyy-mm-dd’. However, we humans prefer date in the format of “dd/mm/yy” or “mm/dd/yy”! So when storing a date field to the database we need to change the date format to ymd, and after retrieving it from the database we need to change it to dmy or mdy.

To make life easier, it has been a while since I have used two functions for these changes. So here I share them, in case a newbie might need it.

function change2dmy($date) //input format: yyyy-m-d
{
$dtmp = explode(“-“,$date);
$dadate = mktime(0,0,0,$dtmp[1],$dtmp[2],$dtmp[0]);
return date(‘d/m/Y’,$dadate);
}
function change2ymd($date) //input format: d/m/yy or yyyy
{
$dtmp = explode(“/”,$date);
$dadate = mktime(0,0,0,$dtmp[1],$dtmp[0],$dtmp[2]);
return date(‘Y-m-d’,$dadate);
}

How to use it: it is a simple function.

<?php

$dmydate = ’24/12/08′
$ymddate = ‘2008-12-24’;

echo change2ymd($dmydate); //output: ‘2008-12-24′
echo change2dmy($ymddate); //output: ’24/12/2008’

?>

Advertisements

, ,

10 Comments