Archive for March, 2009

Dating takes time, women are difficult but PHP?

Wednesday, March 18th, 2009

One of the big annoyances is having a blog or webpage in a certain language and that all the dates appear on your website in English. Of course you can choose just numbered formats, but sometimes the month or the day of the week in words adds that needed little extra polish.

Formatting a date in PHP

Normally a date is formatted like this with the date() function:

[sourcecode language=”php”]
< ?= date(‘d-m-Y’) ?>
[/sourcecode]

Formatting a localised date in PHP

But to format a date in your preferred language you need to use the strftime function:

Format the time and/or date according to locale settings. Month and weekday names and other language-dependent strings respect the current locale set with setlocale().

So we also need the setlocale() function. This function let you set the language to use for the formatting. Your system or server should have them installed, otherwise it’s not possible! And most of them are not installed by default, although easily available.
What does the setlocale() function do:

Returns the new current locale, or FALSE if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid.
An invalid category name also causes a warning message. Category/locale names can be found in RFC 1766 and ISO 639. Different systems have different naming schemes for locales.

Tough pages to consume to be honest, but let’s go on.

Locales settings on your server

You can find the installed localisations in this file on a Linux server:

[sourcecode language=”xml”]
vi var/lib/locales/supported.d/local
[/sourcecode]

My server only had one line by default!
Simply add the one’s you’re missing. You can find all possible localisations in this file:

[sourcecode language=”xml”]
/usr/share/i18n/SUPPORTED
[/sourcecode]

Don’t add them all: it will decrease performance.

So we’re nearly done:

[sourcecode language=”php”]
< ?
setlocale(LC_TIME,’nl-NL.UTF-8′);
echo strftime(‘%s-$b-%y’,time())
?>
[/sourcecode]

You need to enter the correct encoding aswell, otherwise it won’t work. This is dependent of the server settings, so it will influence the portability of your code a bit.
Above code will give you the current date in Dutch, but we need another function to create localised dates from stored timestamps of the MySQL database.

Converting stored Timestamps to PHP understandable format

A MySQL timestamp value won’t work as a direct input to the strftime function. We need to convert it with another function: strtotime.

So we end up with something like this:

[sourcecode language=”php”]
< ?
setlocale(LC_TIME,’nl-NL.UTF-8′);
echo strftime(‘%A %d $b %y’,strtotime($row->timestamp))
?>
[/sourcecode]

Quite a long road to take for a boring date!

Your are browsing
the Archives of My Beloved PHP for March 2009.
Categories
Archives
Links