DateTimeImmutable::createFromFormat
date_create_immutable_from_format
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
DateTimeImmutable::createFromFormat -- date_create_immutable_from_format — Parses a time string according to a specified format
說明
物件導向風格
$format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false過程化風格
$format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false
Returns a new DateTimeImmutable object representing the date and time specified by the
datetime string, which was formatted in the given
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.
The format is parsed from left to right, which means that in some situations the order in which the format characters are present effects the result. In the case of
z(the day of the year), it is required that a year has already been parsed, for example through theYorycharacters.Letters that are used for parsing numbers allow a wide range of values, outside of what the logical range would be. For example, the
d(day of the month) accepts values in the range from00to99. The only constraint is on the amount of digits. The date/time parser's overflow mechanism is used when out-of-range values are given. The examples below show some of this behaviour.The following characters are recognized in the formatparameter stringformatcharacterDescription Example parsable values Day --- --- dandjDay of the month, 2 digits with or without leading zeros 01to31or1to31. (2 digit numbers higher than the number of days in the month are accepted, in which case they will make the month overflow. For example using 33 with January, means February 2nd)DandlA textual representation of a day MonthroughSunorSundaythroughSaturday. If the day name given is different then the day name belonging to a parsed (or default) date is different, then an overflow occurs to the next date with the given day name. See the examples below for an explanation.SEnglish ordinal suffix for the day of the month, 2 characters. It's ignored while processing. st,nd,rdorth.zThe day of the year (starting from 0); must be preceded by Yory.0through365. (3 digit numbers higher than the numbers in a year are accepted, in which case they will make the year overflow. For example using 366 with 2022, means January 2nd, 2023)Month --- --- FandMA textual representation of a month, such as January or Sept JanuarythroughDecemberorJanthroughDecmandnNumeric representation of a month, with or without leading zeros 01through12or1through12. (2 digit numbers higher than 12 are accepted, in which case they will make the year overflow. For example using 13 means January in the next year)Year --- --- XandxA full numeric representation of a year, up to 19 digits, optionally prefixed by +or-Examples: 0055,787,1999,-2003,+10191YA full numeric representation of a year, up to 4 digits Examples: 0055,787,1999,2003yA two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) Examples: 99or03(which will be interpreted as1999and2003, respectively)Time --- --- aandAAnte meridiem and Post meridiem amorpmgandh12-hour format of an hour with or without leading zero 1through12or01through12(2 digit numbers higher than 12 are accepted, in which case they will make the day overflow. For example using14means02in the next AM/PM period)GandH24-hour format of an hour with or without leading zeros 0through23or00through23(2 digit numbers higher than 24 are accepted, in which case they will make the day overflow. For example using26means02:00the next day)iMinutes with leading zeros 00to59. (2 digit numbers higher than 59 are accepted, in which case they will make the hour overflow. For example using66means:06the next hour)sSeconds, with leading zeros 00through59(2 digit numbers higher than 59 are accepted, in which case they will make the minute overflow. For example using90means:30the next minute)vFraction in milliseconds (up to three digits) Example: 12(0.12seconds),345(0.345seconds)uFraction in microseconds (up to six digits) Example: 45(0.45seconds),654321(0.654321seconds)Timezone --- --- e,O,PandTTimezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation Examples: UTC,GMT,Atlantic/Azoresor+0200or+02:00orEST,MDTFull Date/Time --- --- USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Example: 1292177455Whitespace 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: *inY-*-dwith the string2009-aWord-08will matchaWord!Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values ( 0for hour, minute, second and fraction,1for month and day,1970for year andUTCfor timezone information)Without !,all fields will be set to the current date and time.|Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values 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 DateTimeImmutable::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 DateTimeImmutable::getLastErrors().
To include literal characters in
format, you have to escape them with a backslash (\).If
formatdoes not contain the character!then portions of the generated date/time which are not specified informatwill be set to the current system time.If
formatcontains the character!, then portions of the generated date/time not provided informat, as well as values to the left-hand side of the!, will be set to corresponding values from the Unix epoch.If any time character is parsed, then all other time-related fields are set to "0", unless also parsed.
The Unix epoch is 1970-01-01 00:00:00 UTC.
-
datetime -
String representing the time.
-
timezone -
A DateTimeZone object representing the desired time zone.
If
timezoneis omitted ornullanddatetimecontains no timezone, the current timezone will be used.注意:
The
timezoneparameter and the current timezone are ignored when thedatetimeparameter either contains a UNIX timestamp (e.g.946684800) or specifies a timezone (e.g.2010-01-28T15:00:00+02:00).
返回值
Returns a new DateTimeImmutable instance 或者在失敗時返回 false.
更新日誌
| 版本 | 說明 |
|---|---|
| 8.2.0 |
The X and x
format specifiers have been added.
|
| 7.3.0 |
The v format specifier has
been added.
|
範例
示例 #1 DateTimeImmutable::createFromFormat() example
物件導向風格
<?php
$date = DateTimeImmutable::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>
示例 #2 Intricacies of DateTimeImmutable::createFromFormat()
<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d';
$date = DateTimeImmutable::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 = DateTimeImmutable::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 = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = '!d';
$date = DateTimeImmutable::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'i';
$date = DateTimeImmutable::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>
以上例程的輸出類似於:
Current time: 2022-06-02 15:50:46 Format: Y-m-d; 2009-02-15 15:50:46 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 Format: i; 2022-06-02 00:15:00
示例 #3 Format string with literal characters
<?php
echo DateTimeImmutable::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');
?>
以上例程的輸出類似於:
23:15:03
示例 #4 Overflow behaviour
<?php
echo DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97')->format(DateTimeImmutable::RFC2822);
?>
以上例程的輸出類似於:
Sat, 04 Jun 2022 17:01:37 +0000
Although the result looks odd, it is correct, as the following overflows happen:
-
97seconds overflows to1minute, leaving37seconds. -
61minutes overflows to1hour, leaving1minutes. -
35days overflows to1month, leaving4days. The amount of days that are left over depends on the month, as not every month has the same amount of days. -
18months overflows to1year, leaving6months.
示例 #5 Overflowing day name behaviour
<?php
$d = DateTime::createFromFormat(DateTimeInterface::RFC1123, 'Mon, 3 Aug 2020 25:00:00 +0000');
echo $d->format(DateTime::RFC1123), "\n";
?>
以上例程的輸出類似於:
Mon, 10 Aug 2020 01:00:00 +0000
Although the result looks odd, it is correct, as the following overflows happen:
-
3 Aug 2020 25:00:00overflows to(Tue) 4 Aug 2020 01:00. -
Mongets applied, which advances the date toMon, 10 Aug 2020 01:00:00. The explanation of relative keywords such asMonis explained in the section on relative formats.
In order to detect overflows in dates, you can use the DateTimeImmutable::getLastErrors() name, which will include a warning if an overflow occured.
示例 #6 Detecting overflown dates
<?php
$d = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97');
echo $d->format(DateTimeImmutable::RFC2822), "\n\n";
var_dump(DateTimeImmutable::GetLastErrors());
?>
以上例程的輸出類似於:
Sat, 04 Jun 2022 17:01:37 +0000
array(4) {
'warning_count' =>
int(2)
'warnings' =>
array(1) {
[19] =>
string(27) "The parsed date was invalid"
}
'error_count' =>
int(0)
'errors' =>
array(0) {
}
}
參見
- DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
- DateTimeImmutable::getLastErrors() - Returns the warnings and errors
- checkdate() - 驗證一個格里高里日期
- strptime() - 解析由 strftime 產生的日期/時間