PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] How do I format a date with a locale preferred date format with the actual month name?

 March 01, 2022     php, yii     No comments   

Issue

I have a project using Yii that is built to support multiple languages. Using setlocale I can do the following:

setlocale(LC_TIME, 'en_US', 'English');
echo strftime('%x', mktime(0, 0, 0, 12, 25, 2014));

// outputs '12/25/2014'


setlocale(LC_TIME, 'fr_FR', 'French_France')
echo strftime('%x', mktime(0, 0, 0, 12, 25, 2014));

// outputs '25/12/2014'

This is almost what I need, however, I want to print out the actual name of the month in the preferred format not just the numbers. For example, for US English I'd like it to output:

December 25, 2014

And for French I'd like to output:

25 décembre 2014

This has to work for whatever locale is provided (multiple countries) using the specific formatting rules for that locale, French in France and English are just examples. Is there a similar "automatic" way to do this with Yii or just php? Or do I need to save a formatting string along with the locale (not my preffered option)


Solution

Yii's application object has a dateFormatter attribute that gives you access to a CDateFormatter object; you can use this object to format dates according to the application's current language.

You can set this language inside your entry script, or you can defer it until some later point (still before you start generating content of course) such as your base controller's init method.

An example:

$time = mktime(0, 0, 0, 12, 25, 2014);
$app = Yii::app();
$app->language = 'fr_fr'; // yii uses all lowercase

echo $app->dateFormatter->formatDateTime($time, 'long', null);

In the above snippet, 'long' corresponds to the date format d MMMM y for the specified locale (Yii uses the CLDR specification for format strings; this preset is the equivalent of the %x specification in Yii terms) and null instructs the formatter to not include time information in the result at all.

You could also manually specify the format yourself if you wanted to:

echo $app->dateFormatter->format('d MMMM y', $time);


Answered By - Jon
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing