Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting DateTime object, respecting Locale::getDefault()

I have a DateTime object which I'm currently formating via

$mytime->format("D d.m.Y") 

Which gives me exactly the format I need:

Tue 5.3.2012

The only missing point is the correct language. I need German translation of Tue (Tuesday), which is Die (Dienstag).

This gives me the right locale setting

Locale::getDefault() 

But I don't know how to tell DateTime::format to use it.

Isn't there a way to do something like:

$mytime->format("D d.m.Y", \Locale::getDefault()); 
like image 274
stoefln Avatar asked Jan 05 '12 15:01

stoefln


1 Answers

You can use the Intl extension to format the date. It will format dates/times according to the chosen locale, or you can override that with IntlDateFormatter::setPattern().

A quicky example of using a custom pattern, for your desired output format, might look like.

$dt = new DateTime;  $formatter = new IntlDateFormatter('de_DE', IntlDateFormatter::SHORT, IntlDateFormatter::SHORT); $formatter->setPattern('E d.M.yyyy');  echo $formatter->format($dt); 

Which outputs the following (for today, at least).

Di. 4.6.2013

like image 118
salathe Avatar answered Oct 16 '22 22:10

salathe