©
本文档使用 PHP中文网手册 发布
(PHP 5 >= 5.3.0, PHP 7)
DateTime::createFromFormat -- date_create_from_format — Returns new DateTime object formatted according to the specified format
面向对象风格
$format
, string $time
[, DateTimeZone $timezone
] )过程化风格
$format
, string $time
[, DateTimeZone $timezone
] )Returns new DateTime object formatted according to the specified format.
format
The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.
format character | Description | Example parsable values |
---|---|---|
Day | --- | --- |
d and j | Day of the month, 2 digits with or without leading zeros | 01 to 31 or 1 to 31 |
D and l | A textual representation of a day | Mon through Sun or Sunday through Saturday |
S | English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. | st, nd, rd or th. |
z | The day of the year (starting from 0) | 0 through 365 |
Month | --- | --- |
F and M | A textual representation of a month, such as January or Sept | January through December or Jan through Dec |
m and n | Numeric representation of a month, with or without leading zeros | 01 through 12 or 1 through 12 |
Year | --- | --- |
Y | A full numeric representation of a year, 4 digits | Examples: 1999 or 2003 |
y | A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) | Examples: 99 or 03 (which will be interpreted as 1999 and 2003, respectively) |
Time | --- | --- |
a and A | Ante meridiem and Post meridiem | am or pm |
g and h | 12-hour format of an hour with or without leading zero | 1 through 12 or 01 through 12 |
G and H | 24-hour format of an hour with or without leading zeros | 0 through 23 or 00 through 23 |
i | Minutes with leading zeros | 00 to 59 |
s | Seconds, with leading zeros | 00 through 59 |
u | Microseconds (up to six digits) | Example: 45, 654321 |
Timezone | --- | --- |
e, O, P and T | Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation | Examples: UTC, GMT, Atlantic/Azores or +0200 or +02:00 or EST, MDT |
Full Date/Time | --- | --- |
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Example: 1292177455 |
Whitespace and Separators | --- | --- |
(space) | One space or one tab | Example: |
# | One of the following separation symbol: ;, :, /, ., ,, -, ( or ) | Example: / |
;, :, /, ., ,, -, ( or ) | The specified character. | Example: - |
? | A random byte | Example: ^ (Be aware that for UTF-8 characters you might need more than one ?. In this case, using * is probably what you want instead) |
* | Random bytes until the next separator or digit | Example: * in Y-*-d with the string 2009-aWord-08 will match aWord |
! | Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch | Without !, all fields will be set to the current date and time. |
| | Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch if they have not been parsed yet | Y-m-d| will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0. |
+ | If this format specifier is present, trailing data in the string will not cause an error, but a warning instead | Use DateTime::getLastErrors() to find out whether trailing data was present. |
Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTime::getLastErrors() .
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.
If timezone
is omitted and
time
contains no timezone,
the current timezone will be used.
Note:
The
timezone
parameter and the current timezone are ignored when thetime
parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
Returns a new DateTime instance 或者在失败时返回 FALSE
.
版本 | 说明 |
---|---|
5.3.9 |
The + format specifier has been added.
|
Example #1 DateTime::createFromFormat() example
面向对象风格
<?php
$date = DateTime :: createFromFormat ( 'j-M-Y' , '15-Feb-2009' );
echo $date -> format ( 'Y-m-d' );
?>
过程化风格
<?php
$date = date_create_from_format ( 'j-M-Y' , '15-Feb-2009' );
echo date_format ( $date , 'Y-m-d' );
?>
以上例程会输出:
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" ;
?>
以上例程的输出类似于:
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
[#1] Albie at aveit dot org [2015-11-22 18:58:45]
If you want to safely compare equality of a DateTime object without explicitly providing the time portion make use of the ! format character.
<?php
$date1 = DateTime::createFromFormat('!Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('!Y-m-d', '2012-10-17');
?>
If you omit the ! format character without explicitly providing the time portion your timestamp which will include the current system time in the stamp.
<?php
$date1 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date1 == $date2); //will be false
var_dump($date1 >= $date2); //will be false
var_dump($date1 < $date2); //will be true
?>
[#2] chernomyrdin at gmail dot com [2015-11-19 11:39:15]
<?php
$date = DateTime::createFromFormat('U.u', microtime(TRUE));
var_dump($date->format('Y-m-d H:i:s.u'));
?>
will print: 2015-11-19 11:37:29.125300 (the current time with microseconds)
[#3] jplevene [2015-06-12 15:09:43]
To convert an email header date use the following (important, notice the * at the end)
$date = DateTime::createFromFormat('D, d M Y H:i:s O *', $email_date);
Some dates in email headers can be formatted as:
Fri, 12 Jun 2015 13:53:37 +0000 (UTC)
The "(UTC)" at the end of the date causes an error and will return a result of false unless the * is at the end.
[#4] SeliusX [2015-01-30 14:37:46]
Creating timestamps to the day can result in hidden bugs cause hours are taken from now:
Example:
$newDateTime = DateTime::createFromFormat('Y-m-d', '2014-12-10');
$newDateTime->format('H') != '00';
Better use time too or erase the values later on:
$newDateTime = DateTime::createFromFormat('Y-m-d h:i', '2014-12-10 00:00');
or:
$newDateTime = DateTime::createFromFormat(''Y-m-d', '2014-12-10');
$newDateTime->setTime(0, 0);
[#5] ELPI [2014-10-31 10:04:17]
It can be confusing creating new DateTime from timestamp when your default timezone (date.timezone) is different from UTC and you are used to date()-function.
date()-function automatically uses your current timezone setting but DateTime::createFromFormat (or DateTime constructor) does not (it ignores tz-parameter).
You can get same results as date() by setting the timezone after object creation.
<?php
$ts = 1414706400;
$date1 = date("Y-m-d H:i", $ts);
$date2 = DateTime::createFromFormat("U", $ts)->setTimeZone(new DateTimeZone(date_default_timezone_get()))->format("Y-m-d H:i");
//$date1===$date2
?>
[#6] nicodoggie at gmail dot com [2014-06-25 13:20:07]
I've found that on PHP 5.5.13 (not sure if it happens on other versions) if you enter a month larger than 12 on a format that takes numeric months, the result will be a DateTime object with its month equal to the number modulo 12 instead of returning false.
<?php
var_dump(DateTime::createFromFormat('Y-m-d', '2013-22-01'));
?>
results in:
class DateTime#4 (3) {
public $date =>
string(19) "2014-10-01 13:05:05"
public $timezone_type =>
int(3)
public $timezone =>
string(3) "UTC"
}
[#7] d dot shankarnarayana at gmail dot com [2014-03-24 18:46:43]
Say if there is a string with $date = "today is 2014 January 1"; and you need to extract "2014 January" using DateTime::createFromFormat(). As you can see in the string there is something odd like "today is" .Since that string (today is) does not correspond to a date format, we need to escape that.
In this case, each and every character on that string has to be escaped as shown below.
The code.
<?php
$paragraph = "today is 2014 January 1";
$date = DateTime::createFromFormat('\t\o\d\a\y \i\s Y F j', $paragraph);
echo $date->format('Y F'); //"prints" 2014 January
- Shankar Damodaran
[#8] mail at marcel-juenemann dot de [2013-01-17 17:24:23]
Note that the U option does not support negative timestamps (before 1970). You have to use date for that.
[#9] falundir at gmail dot com [2012-10-17 12:03:16]
Be warned that DateTime object created without explicitely providing the time portion will have the current time set instead of 00:00:00.
<?php
$date = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date->format('Y-m-d H:i:s')); //will print 2012-10-17 13:57:34 (the current time)
?>
That's also why you can't safely compare equality of such DateTime objects:
<?php
$date1 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date1 == $date2); //will be false
var_dump($date1 >= $date2); //will be false
var_dump($date1 < $date2); //will be true
?>
[#10] thomas dot ribiere at allgoob dot com [2012-08-30 15:46:35]
Not a bug, but a strange issue today 2012-08-30 :
<?php
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m",$date);
echo $d->format("Y-m");
?>
will display :
2011-02
2011-03
It's because there is no 2011-02-30, so datetime will take march insteed of february ...
To fix it :
<?php
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");
?>
[#11] kamil dot wegrzynowicz at baobaz dot com [2012-02-10 08:05:50]
It seems that a pipe ('|') option in formating string works only with PHP version 5.3.7 and newer. We had an issue with it on versions 5.3.2, 5.3.3, 5.3.6. Yet it was fine with 5.3.8 and 5.3.10.
By short example:
<?php
$timezone = new DateTimeZone('UTC');
$dateTime = DateTime::createFromFormat('dmY|', '01011972', $timezone);
//$dateTime is FALSE in PHP v <5.3.8
?>
Instead we used a workaround:
<?php
$dateTime = DateTime::createFromFormat('dmY', '01011972', $timezone);
$dateTime->format('Y-m-d 00:00:00');
?>
which works fine.
====
Modified by admin to correct for version (5.3.7 not 5.3.8)
[#12] Aurelien Marchand [2011-03-29 07:13:55]
Beware specifying a timezone in the format as it will take precedence over the DateTimeZone object.
<?php
$timezone = "UTC"; // or any other valid name for a timezone
$d= DateTime::createFromFormat("Y-m-d H:i:s T","2011-11-06 00:00:00 EDT",new DateTimeZone($timezone));
echo $d->format("Y-m-d H:i:s T - U");
// returns "2011-11-06 00:00:00 EDT - 1320552000"
// specifying $timezone = "Pacific/Honolulu"; would return the same string
?>
This gets hairy when you are playing with transition from summer time to winter time! For instance, in Toronto, the time change happens on 2011-11-06. One second after 01:59:59 (EDT), the time becomes 01:00:00 (EST), or 1320559200 in Unix timestamp.
However, notice the following:
<?php
$d = DateTime::createFromFormat("Y-m-d H:i:s","2011-11-06 01:00:00",new DateTimeZone("EST"));
echo $d->format("Y-m-d H:i:s T U");
// returns "2011-11-06 01:00:00 EDT 1320555600" instead of "2011-11-06 01:00:00 EST 1320559200"
// so the correct way is to do:
$d = DateTime::createFromFormat("Y-m-d H:i:s T","2011-11-06 01:00:00 EST",new DateTimeZone($timezone)); // set $timezone to any valid string for DateTimeZone, it doesn't matter
echo $d->format("Y-m-d H:i:s T U");
// returns "2011-11-06 01:00:00 EST - 1320559200" as wanted
?>
[#13] klugg at tlen dot pl [2011-03-14 09:52:30]
In order to use a DateTimeZone, don't enter one of the DateTimeZone::Europe, DateTimeZone::Asia etc. constants, but create a DateTimeZone object with verbal timezone name passed as a string:
<?php
$eventDate = DateTime::createFromFormat('m/d/y h:i', '02/26/11 08:00', new DateTimeZone('Europe/Warsaw'));
echo date_format($eventDate, 'Y-m-d'); //prints "2011-02-26"
?>