Thursday, October 11, 2007

Handling dates

It is normal to have to change the format of a date to suit one type of database, or to be presented to a user. Usually, strtotime is a good tool to do so because it supports the traditional format of MySQL and many others, but the problem is usually when we get a date format dd/ mm/yy, because by default this feature takes American format mm/dd/yy and can be confused with the 01/07 January 7, instead of July 1 that we expected. The solution offered by PHP is the function strptime, which allows us to indicate the format of the date. However, this feature is quite new (since PHP 5.1.0) and is not implemented on Windows, which is quite limited. Therefore, we can create a small function, for this purpose.

function strtotime2($date)
{
if (preg_match('#^((0?[1-9])|([1-2]?[0-9])|(3[0-1]))/(0?[1-9]|(1[0-2]))/((19|20)?([0-9]{2}))$#', $date))
{
list($day, $month, $year) = explode('/', $date);
return mktime(0, 0, 0, $month, $day, $year);
} else
{
return strtotime($date);
}
}

No comments: