PHP | DateTime format() Function

The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.

Syntax:

  • Object oriented style
    string DateTime::format( string $format )

    or



    string DateTimeImmutable::format( string $format )

    or

    string DateTimeInterface::format( string $format )
  • Procedural style
    string date_format( DateTimeInterface $object, string $format )

Parameters: This function uses two parameters as mentioned above and described below:

  • $object: This parameter holds the DateTime object.
  • $format: This parameter holds the format accepted by date() function.

Return Value: This function return the new formatted date string on success or False on failure.

Below programs illustrate the DateTime::format() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialising the DateTime() object with a date
$datetime = new DateTime('2019-09-30');
  
// Calling the format() function with a 
// specified format 'd-m-Y'
echo $datetime->format('d-m-Y');
  
?>

chevron_right


Output:

30-09-2019

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Initialising the DateTime() object with a date
$datetime = new DateTime('2019-09-30');
  
// Calling the format() function with a 
// specified format 'd-m-Y H:i:s'
echo $datetime->format('d-m-Y H:i:s');
  
?>

chevron_right


Output:

30-09-2019 00:00:00

Reference: https://www.php.net/manual/en/datetime.format.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.