English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial básico PHP

Tutorial avançado PHP

PHP & MySQL

Manual de referência PHP

Uso e exemplo da função PHP date_create_immutable_from_format()

Manual do PHP Date & Time Functions

A função date_create_immutable_from_format() analisa strings de data conforme o formato especificado

Definição e uso

A função date_create_immutable_from_format() possui o alias DateTimeImmutable::createFromFormat(). Ela aceita uma string de data e uma string de formato como parâmetros, para analisar a string de data fornecida no formato especificado e retornar um objeto DateTimeImmutable.

Sintaxe

date_create_immutable_from_format($date, $time [,$timezone])

Parameter

Serial NumberParameters and Description
1

format (required)

This is a string value representing the format of the time string you need to parse.

2

time (required)

This is a string value representing the time you need to parse.

3

timezone (optional)

This is an object of the DateTimeZone class representing the required timezone.

Return Value

The date_create_immutable_from_format() function returns a DateTime object representing the parsed time. If it fails, this function returns a boolean valuefalse.

PHP Version

This function was initially introduced in PHP version5.5introduced in version 7.0 and can be used in all higher versions.

Online Examples

The following examples demonstratedate_create_immutable_from_format()Function Usage-

<?php
   //Create a DateTime object
   $date = "1989-08-25";
   $format = "Y-m-d";
   $res = date_create_immutable_from_format($format, $date);
   print("Date: ".date_format($res, "Y-m-d"));
?>
Test and see‹/›

Output Results

Date: 1989-08-25

Online Examples

Now, let's try passing the optional timezone parameter-

<?php
   //Create a DateTime object
   $date = "1989-08-25";
   $format = "Y-m-d";
   $tz = new DateTimeZone('Asia/Shanghai');  
   $res = date_create_immutable_from_format($format, $date, $tz);
   print date_format($res, "Y-m-d");
?>
Test and see‹/›

Output Results

1989-08-25

Online Examples

The following examples demonstrate the usage of date_create_immutable_from_format() with different formats-

<?php
   $res1 = date_create_immutable_from_format("j.n.Y", "25.8.2014");
   print(date_format($res1, "Y-m-d"));
   print("\n");
   $res2 = date_create_immutable_from_format('Y-d-m H:i:s', '2014-25-08 12:20:25');
   print(date_format($res2, "Y-m-d H:i:s"));  
?>
Test and see‹/›

This will produce the following output-

2014-08-25
2014-08-25 12:20:25