DateTime::format
DateTimeImmutable::format
DateTimeInterface::format
date_format
(PHP 5 >= 5.2.0)
DateTime::format -- DateTimeImmutable::format -- DateTimeInterface::format -- date_format — Returns date formatted according to given format
Description
Object oriented style
public string DateTime::format
( string
$format
)
public string DateTimeImmutable::format
( string
$format
)
public string DateTimeInterface::format
( string
$format
)Procedural style
Returns date formatted according to given format.
Parameters
-
object
-
Procedural style only: A DateTime object returned by date_create()
-
format
-
Format accepted by date().
Return Values
Returns the formatted date string on success or FALSE
on failure.
Examples
Example #1 DateTime::format() example
Object oriented style
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Procedural style
<?php
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
?>
The above example will output:
2000-01-01 00:00:00
Notes
This method does not use locales. All output is in English.
See Also
- date() - Format a local time/date
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с датой и временем
- Дата и Время
- Функция DateTime::diff() - Возвращает разницу между двумя DateTime объектами
- Функция DateTime::format() - Возвращает дату, отформатированную согласно переданному формату
- Функция DateTime::getOffset() - Возвращает смещение часовой зоны
- Функция DateTime::getTimestamp() - Возвращает временную метку Unix
- Функция DateTime::getTimezone() - Возвращает часовую зону относительно текущему значению DateTime
- Функция DateTime::__wakeup() - Обработчик __wakeup
Коментарии
If you want to get the week of year + year of said week, you need to use `format('o-W'), otherwise you can stumble into a non-obvious gotcha (unless you RTFM and memorised it, that is).
Using `Y` instead of `o` can result in incorrect year values in the case of the first or last week of the year (depending on if January 4th falls into said week or not), such as the first week of 2025 between 2024-12-30 and 2025-01-05 - `(new DateTime('2024-12-30'))->format('o-W')` will return the correct value of `2025-01` (as per ISO-8601 definition of week of year), while `format('Y-W')` will return `2024-01`.
Because of this, I would personally recommend avoiding using week of year anywhere unless absolutely necessary, as it is easy to make this mistake and never realise it.