Showing posts with label Date. Show all posts
Showing posts with label Date. Show all posts

Thursday, November 8, 2007

Naming dates (not in english)

It is very common to the problem of wanting to put "November 8, 2007" in a language different from english... In general, a switch is used to translate the name of the month, but there is a much simpler way to do it. PHP brings the ability to configure the location, and then select "regional" settings like language, currency, numbers.

To do so, we must first set the region with setlocale and then we can use the date format with strftime

Example
setlocale(LC_ALL, 'sp');
echo strftime('%d de %B de %Y');
?>

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);
}
}