Date and time
In MV, date and time are stored in model fields of the date and date_time types. In the database, they are stored in the SQL format of the form 'yyyy-mm-dd hh:mm:ss'. When entering and retrieving data from the database, it is necessary to use special methods to convert the values to the desired format, using the I18n class, which is also responsible for internationalization and localization.
The main date format is specified in the localization file, which is located in the /adminpanel/i18n/[region]/locale.php folder.
I18n class methods
- formatDate($date [,$format]) - converts the date from the SQL format ‘yyyy-mm-dd hh:mm:ss’ to the current format specified in the localization file, if you pass an optional parameter in the form of 'only-date', it will return only the date, and if in the form of 'no-seconds', the seconds will be discarded. Also, the date format can be passed in a form similar to the PHP function date(), for example ‘d-m-Y’.
- dateForSQL($date) - converts the date from the current format to the SQL format, for writing to the database.
- getCurrentDate([$sql_format]) - returns the current date in accordance with the localization format. If you pass an optional parameter as 'SQL', the current date will be returned in SQL format.
- getCurrentDateTime([$sql_format]) - returns the current date and time according to the localization format.
- timestampToDate($timestamp) - converts a timestamp to a date according to the localization format. If you pass an optional parameter as 'SQL', the current date will be returned in SQL format.
- getMonth($number) - returns the name of the month by its number, for example 'February', 'March'.
- getMonthCase($number) - returns the name of the month in the genitive case, for example 'February', 'March'.
- getWeekDayName($date) - returns the name of the day of the week, for example 'Tuesday', 'Thursday'
//Find news by id
$record = $mv -> news -> find(32);
//Output date, converting SQL format
echo I18n::formatDate($record -> date);
//Format date
echo I18n::formatDate($record -> date, 'd/m/Y'));
//Output date and time without seconds
echo I18n::formatDate($record -> date, 'no-seconds');
//Output only date, without time (for date_time)
echo I18n::formatDate($record -> date, 'only-date');
//Output the day of the week
echo I18n::getWeekDayName($record -> date);
//Pass the current date into the record
$record -> date = I18n::getCurrentDateTime();
$record -> update();
//Count the number of news items for the current day
$number = $news -> countRecords(['date' => I18n::getCurrentDate()]);
//Converting a date from SQL to the format 'November 12, 2023'
public function formatDate($date)
{
$date = explode('-', $date);
return $date[2].' '.I18n::getMonthCase(intval($date[1])).' '.$date[0];
}
Previous section
Files and images