234 of 410 menu

The format Method of the DateTime Class

The format method is applied to a DateTime object and returns a formatted date/time string. It accepts a format string as a parameter, where special characters are replaced with date components. The string format is similar to the date function.

Syntax

$datetime->format(string $format);

Example

Formatting the current date in Y-m-d format:

<?php $date = new DateTime(); echo $date->format('Y-m-d'); ?>

Code execution result:

'2025-07-30'

Example

Getting the time in H:i:s format:

<?php $date = new DateTime(); echo $date->format('H:i:s'); ?>

Code execution result:

'14:25:36'

Example

Getting complete date information:

<?php $date = new DateTime(); echo $date->format('Y-m-d H:i:s'); ?>

Code execution result:

'2025-07-30 14:25:36'

See Also

  • the date function,
    which formats a timestamp
  • the strtotime function,
    which converts a textual date description
byenru