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 | Description | 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:
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 dateecho date_format($date, 'Y-m-d');?> |
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 dateecho date_format($date, 'Y-m-j');?> |
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 dateecho $date->format('Y-m-d');?> |
2019-10-03
Reference: https://www.php.net/manual/en/datetimeimmutable.createfromformat.php



