Working with Date in Yii 2.0

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:

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.

 

2. Using format() method  and format name:

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:

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:

Like this Post? Share