PHP | date_create_immutable_from_format() Function

Last Updated : 06 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 characterDescriptionExample returned values
jDay of the month without leading zeros1 to 31
dDay of the month with leading zeros01 to 31
mNumeric representation of the month01 to 12
MShort textual representation of the monthJan to Dec
YRepresentation of a year1989, 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:  

PHP
<?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');

?>

Output: 
2019-10-03

 

Program 2: 

PHP
<?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');

?>

Output: 
2019-10-3

 

Program 3: 

PHP
<?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');

?>

Output: 
2019-10-03

 

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


Next Article

Similar Reads