PHP Velho Oeste 2024

date_parse_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_parse_from_format指定した書式でフォーマットされた日付についての情報を取得する

説明

date_parse_from_format(string $format, string $datetime): array

指定した日付/時刻についての詳細情報を連想配列で返します。

パラメータ

format

format の使い方に関するドキュメントは、 DateTimeImmutable::createFromFormat() のそれを参照ください。同じルールが適用されます。

datetime

日付/時刻をあらわす文字列。

戻り値

指定した日付/時刻についての詳細情報を連想配列で返します。

返される配列は、 year, month, day, hour, minute, second, fraction, is_localtime というキーを持ちます。

is_localtime が存在する場合、 zone_type がタイムゾーンのタイプを示します。 タイプ 1 (UTC オフセット) の場合、 zoneis_dst フィールドが追加されます。 タイプ 2 (省略形) の場合、 tz_abbris_dst フィールドが追加されます。 タイプ 3 (タイムゾーン識別子) の場合、 tz_abbr, tz_id が追加されます。

warning_countwarnings が配列に含まれます。 最初のフィールドは、警告が何個発生したかを示します。 warnings 配列は、 警告を説明する文字列と一緒に、指定された datetime のどの場所で警告が発生したかの位置を示します。 下記の例で、警告の例を示します。

error_count, errors フィールドも配列に含まれます。 最初のフィールドは、エラーが何個発生したかを示します。 errors 配列のキーは、 警告を説明する文字列と一緒に、指定された datetime のどの場所でエラーが発生したかの位置を示します。 下記の例で、エラーの例を示します。

警告

warningserrors に含まれる配列の要素数は、 同じ箇所でエラーや警告が発生した場合、 warning_counterror_count よりも少なくなる可能性があります。

エラー / 例外

datetime に NULLバイトが含まれている場合は、 ValueError がスローされます。

変更履歴

バージョン 説明
8.0.21, 8.1.8, 8.2.0 datetime に NULLバイトが含まれている場合は、 ValueError がスローされるようになりました。 これより前のバージョンでは、こうした値は静かに無視されていました。
7.2.0 返される配列の zone 要素が、 分ではなく秒を表すようになり、 符号が逆になりました。 たとえば、 -1207200 を表すようになります。

例1 date_parse_from_format() の例

<?php
$date
= "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>

上の例の出力は以下となります。

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] =>
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => 3600
    [is_dst] =>
)

例2 date_parse_from_format() の結果に警告が含まれる例

<?php
$date
= "26 August 2022 22:30 pm";
$parsed = date_parse_from_format("j F Y G:i a", $date);

echo
"Warnings count: ", $parsed['warning_count'], "\n";
foreach (
$parsed['warnings'] as $position => $message) {
echo
"\tOn position {$position}: {$message}\n";
}
?>

上の例の出力は以下となります。

Warnings count: 1
	On position 23: The parsed time was invalid

例3 date_parse_from_format() の結果にエラーが含まれる例

<?php
$date
= "26 August 2022 CEST";
$parsed = date_parse_from_format("j F Y H:i", $date);

echo
"Errors count: ", $parsed['error_count'], "\n";
foreach (
$parsed['errors'] as $position => $message) {
echo
"\tOn position {$position}: {$message}\n";
}
?>

上の例の出力は以下となります。

Errors count: 3
	On position 15: A two digit hour could not be found
	On position 19: Data missing

参考

add a note add a note

User Contributed Notes 2 notes

up
20
Archetrix
9 years ago
For use in Versions prior V5.3:

<?php
if (!function_exists('date_parse_from_format')) {

    function
date_parse_from_format($format, $date) {
       
// reverse engineer date formats
       
$keys = array(
           
'Y' => array('year', '\d{4}'),
           
'y' => array('year', '\d{2}'),
           
'm' => array('month', '\d{2}'),
           
'n' => array('month', '\d{1,2}'),
           
'M' => array('month', '[A-Z][a-z]{3}'),
           
'F' => array('month', '[A-Z][a-z]{2,8}'),
           
'd' => array('day', '\d{2}'),
           
'j' => array('day', '\d{1,2}'),
           
'D' => array('day', '[A-Z][a-z]{2}'),
           
'l' => array('day', '[A-Z][a-z]{6,9}'),
           
'u' => array('hour', '\d{1,6}'),
           
'h' => array('hour', '\d{2}'),
           
'H' => array('hour', '\d{2}'),
           
'g' => array('hour', '\d{1,2}'),
           
'G' => array('hour', '\d{1,2}'),
           
'i' => array('minute', '\d{2}'),
           
's' => array('second', '\d{2}')
        );

       
// convert format string to regex
       
$regex = '';
       
$chars = str_split($format);
        foreach (
$chars AS $n => $char) {
           
$lastChar = isset($chars[$n - 1]) ? $chars[$n - 1] : '';
           
$skipCurrent = '\\' == $lastChar;
            if (!
$skipCurrent && isset($keys[$char])) {
               
$regex .= '(?P<' . $keys[$char][0] . '>' . $keys[$char][1] . ')';
            } else if (
'\\' == $char) {
               
$regex .= $char;
            } else {
               
$regex .= preg_quote($char);
            }
        }

       
$dt = array();
       
$dt['error_count'] = 0;
       
// now try to match it
       
if (preg_match('#^' . $regex . '$#', $date, $dt)) {
            foreach (
$dt AS $k => $v) {
                if (
is_int($k)) {
                    unset(
$dt[$k]);
                }
            }
            if (!
checkdate($dt['month'], $dt['day'], $dt['year'])) {
               
$dt['error_count'] = 1;
            }
        } else {
           
$dt['error_count'] = 1;
        }
       
$dt['errors'] = array();
       
$dt['fraction'] = '';
       
$dt['warning_count'] = 0;
       
$dt['warnings'] = array();
       
$dt['is_localtime'] = 0;
       
$dt['zone_type'] = 0;
       
$dt['zone'] = 0;
       
$dt['is_dst'] = '';
        return
$dt;
    }

}
?>

Not my invention though. I found it here: http://stackoverflow.com/questions/6668223/php-date-parse-from-format-alternative-in-php-5-2

Thought this might be a good place to keep a copy in case someone stumbles upon the same problem facing outdated PHP versions on customer servers ....
up
1
gilles dot migliori at gmail dot com
5 years ago
$date = "10 October 2018 19:30 pm";
print_r (date_parse_from_format("j F Y G:i a", $date));

Output:

Array (
    [year]          => 2018
    [month]         => 10
    [day]           => 10
    [hour]          => 31
    [minute]        => 30
    [second]        => 0
    [fraction]      =>
    [warning_count] => 1
    [warnings]      => Array (
                        [24] => The parsed time was invalid
                    )
    [error_count]   => 0
    [errors]        => Array ( )
    [is_localtime]  =>
)

19:30 pm is invalid, 24-hour format of an hour can't be used with am/pm

must be replaced with:

$date = "10 October 2018 19:30";
print_r (date_parse_from_format("j F Y G:i", $date));

or:

$date = "10 October 2018 7:30 pm";
print_r (date_parse_from_format("j F Y g:i a", $date));
To Top