This website recently got a major rebuild; if you're missing something, let Lorna know.

Locale-Sensitive Dates in PHP



I am working on a site at the moment whose front end is in Dutch - and for an English-only speaker, its an education! Most things default to English and I had no idea how to use PHP to work with other languages.

In particular I needed dates like "Donderdag 23 Oktober", and I was sure PHP should know how to do this without me creating arrays for days of the week and months of the year. With some help from my friend (thanks Derick) I discovered that there is a date function in PHP that takes into account the locale of the script, called strftime. The machine needs to have the locale already installed, then you can just do:

setlocale(LC_TIME, 'nl_NL.UTF-8');
return ucwords(strftime('%A %e %B',$publish_date));

Setlocale() will return false if the language isn't available on the host system, so its possible to check and maybe try a few likely ones or let the user know. This was useful to me and will work for other languages too - you just need the locale installed and then set with setlocale.


In: php
Tags: #php