Yii is a powerful framework where a lot of things happen automagically but learning curves are more complex as compared to any other PHP MVC framework. The first part (before ‘but‘ in first line) attracts beginners to learn and experience it while the later part makes them stressed. So I tried here in article Working with Date in Yii 2.0 to simplify the concept by taking ‘Date‘ as point.
Although I have picked Date for ease still you can be familiar with Data Formatter helper available in Yii while reading this post which will sure help you to work with formatting other data such as date/time values, numbers and other commonly used formats.
Working with Date in Yii 2.0
yii\i18n\Formatter
helper class provides properties and methods to format data and represent it to user in more readable way. We can either use methods available there or use a combination of format name and format()
method.
1. Using asDate()
formatting method:
1 | Yii::$app->formatter->asDate('DATE VALUE', 'DATE FORMAT'); |
This method requires two parameter. First is a value that can be parsed to create a DateTime object. I usually pass a date field from MySQL table or timestamp value as well.
The second parameter makes a few people confused if they did never hear about ICU manuals. This can be either one among “short“, “medium“, “long“, and “full” or a custom format as specified in the ICU manual.
Moreever you can put a PHP date format string there by prefixing it with php:
Let’s take few examples.
1 2 3 4 5 6 7 8 9 10 11 | // ICU date format for locale echo Yii::$app->formatter->asDate('2015-01-20', 'long'); // output: January 20, 2015 // ICU format echo Yii::$app->formatter->asDate('now', 'yyyy-MM-dd'); // Output: 2015-01-20 // PHP date() format echo Yii::$app->formatter->asDate('now', 'php:Y-m-d'); // Output: 2015-01-20 |
2. Using format()
method and format name:
1 | Yii::$app->formatter->format( $value, $format ) |
In our example here, the $value
would be a date and the $format
would be ‘date‘ (in general: html, text, time, email etc.). You can set the format in Yii configuration file. Head to your project -> config -> web.php
file and place $dateFormat
as per ICU manual or php:
syntex under components:
1 2 3 4 5 6 7 8 9 10 11 12 | $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'defaultRoute' => 'site/index', 'components' => [ 'formatter' => [ 'dateFormat' => 'MMMM dd, yyyy', ] , 'urlManager' => [ ... |
You can get a full list of methods and properties in Yii Data Formatter helper here.
Let’s check a few more examples to be more familiar to Working with Date in Yii 2.0:
1 2 3 4 5 6 7 8 9 10 | // With format method echo Yii::$app->formatter->format('2015-01-20', 'date'); //Output: January 20, 2015 // Using fields returned by MySQL $dob = Yii::$app->formatter->format($profile['date_of_birth'], 'date'); // Set max age $timestamp = strtotime('-13 years -1 day'); $max_age = Yii::$app->formatter->format($timestamp, 'date'); |