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

php$datetime->format(string $format);

Example

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

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

Code execution result:

php'2025-07-30'

Example

Getting the time in H:i:s format:

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

Code execution result:

php'14:25:36'

Example

Getting complete date information:

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

Code execution result:

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

See Also

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