DateTime
PHP Manual

DateTime::createFromFormat

(PHP 5 >= 5.3.0)

DateTime::createFromFormatReturns new DateTime object formatted according to the specified format

Description

Object oriented style

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Procedural style

DateTime date_create_from_format ( string $format , string $time [, DateTimeZone $timezone ] )

Returns new DateTime object formatted according to the specified format.

Parameters

format

Format accepted by date().

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC.

time

String representing the time.

timezone

A DateTimeZone object representing the desired time zone.

Return Values

Returns a new DateTime instance or FALSE on failure.

Examples

Example #1 DateTime::createFromFormat() example

Object oriented style

<?php
$date 
DateTime::createFromFormat('j-M-Y''15-Feb-2009');
echo 
$date->format('Y-m-d');
?>

Procedural style

<?php
$date 
date_create_from_format('j-M-Y''15-Feb-2009');
echo 
date_format($date'Y-m-d');
?>

The above examples will output:

2009-02-15

Example #2 Intricacies of DateTime::createFromFormat()

<?php
echo 'Current time: ' date('Y-m-d H:i:s') . "\n";

$format 'Y-m-d';
$date DateTime::createFromFormat($format'2009-02-15');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format 'Y-m-d H:i:s';
$date DateTime::createFromFormat($format'2009-02-15 15:16:17');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format 'Y-m-!d H:i:s';
$date DateTime::createFromFormat($format'2009-02-15 15:16:17');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format '!d';
$date DateTime::createFromFormat($format'15');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";
?>

The above example will output something similar to:

Current time: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00

See Also


DateTime
PHP Manual