232 of 410 menu

The createFromFormat Method of the DateTime Class

The static method createFromFormat of the DateTime class allows creating a DateTime object from a string that matches the specified format. It accepts three parameters: the date format, a string with the date, and an optional DateTimeZone object. Returns a DateTime object or false in case of an error.

Syntax

DateTime::createFromFormat( string $format, string $datetime, DateTimeZone $timezone = null ): DateTime|false

Example

Let's create a date from a string in the day-month-year format:

<?php $date = DateTime::createFromFormat('d-m-Y', '15-07-2023'); echo $date->format('Y-m-d'); ?>

Code execution result:

'2023-07-15'

Example

Let's create a date and time from a string in a non-standard format:

<?php $date = DateTime::createFromFormat('Y/m/d H:i', '2023/07/15 14:30'); echo $date->format('d.m.Y H:i:s'); ?>

Code execution result:

'15.07.2023 14:30:00'

Example

Let's create a date with a timezone specified:

<?php $timezone = new DateTimeZone('Europe/Moscow'); $date = DateTime::createFromFormat('Y-m-d H:i:s', '2023-07-15 14:30:00', $timezone); echo $date->format('Y-m-d H:i:s e'); ?>

Code execution result:

'2023-07-15 14:30:00 Europe/Moscow'

See Also

  • the format method,
    which formats the date and time
  • the strtotime function,
    which converts a textual date description into a timestamp
byenru