PHP | date_create_immutable_from_format() Function

The date_create_immutable_from_format() function is an inbuilt function in PHP which is used to parse a time string according to the specified format.

Syntax:

  • Object oriented style:
    DateTimeImmutable static DateTime::createFromFormat( string $format,
                                          string $time, DateTimeZone $timezone )
  • Procedural style:
    DateTimeImmutable date_create_from_format( string $format, 
                                          string $time, DateTimeZone $timezone )

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



  • $format: This parameter holds the DateTime format in string.
  • $time: This parameter holds the time in string format.
  • $timezone: This parameter holds the DateTimeZone object.

Return Value: This function returns a new DateTimeImmutable object representing the date and time specified by the time string, which was formatted in the given format.

Characters and its description:

Format character Desciption Example returned values
j Day of the month without leading zeros 1 to 31
d Day of the month with leading zeros 01 to 31
m Numeric representation of the month 01 to 12
M Short textual representation of the month Jan to Dec
Y Representation of a year 1989, 2017

The format string can be a combination of any of the format characters in any order but we would have to provide the input date-time string in the same order.

Below programs illustrate the date_create_immutable_from_format() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Use date_create_from_format() function
// to create a date format
$date = date_create_from_format('j-M-Y', '03-oct-2019');
  
// Display the date
echo date_format($date, 'Y-m-d');
  
?>

chevron_right


Output:

2019-10-03

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Use date_create_from_format() function
// to create a date format
$date = date_create_from_format('d-M-Y', '03-oct-2019');
  
// Display the date
echo date_format($date, 'Y-m-j');
  
?>

chevron_right


Output:

2019-10-3

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Use DateTime::createFromFormat() function
// to create a date object
$date = DateTime::createFromFormat('j-M-Y', '03-oct-2019');
  
// Display the date
echo $date->format('Y-m-d');
  
?>

chevron_right


Output:

2019-10-03

Reference: https://www.php.net/manual/en/datetimeimmutable.createfromformat.php




My Personal Notes arrow_drop_up


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.