0

Why date_parse does not recognise years in a string?

<?php
$string = "Saturday, 23 March, 2013";
print_r(date_parse($string));
?>

result,

Array
(
    [year] => 
    [month] => 3
    [day] => 23
    [hour] => 20
    [minute] => 13
    [second] => 0
    [fraction] => 0
    [warning_count] => 0
    [warnings] => Array
        (
        )

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

    [is_localtime] => 
    [relative] => Array
        (
            [year] => 0
            [month] => 0
            [day] => 0
            [hour] => 0
            [minute] => 0
            [second] => 0
            [weekday] => 6
        )

)
Charles
  • 50,943
  • 13
  • 104
  • 142
Run
  • 54,938
  • 169
  • 450
  • 748
  • 1
    if you KNOW the format of a date you need to parse, then don't try and depend on PHP's own parsing abilities. You WILL get burned at some point. for fixed formats, always use things like date_create_from_format() and eliminate the guesswork. – Marc B Mar 13 '13 at 19:21
  • thanks. But I am not sure what is the benefits of `date_create_from_format`... – Run Mar 13 '13 at 19:37
  • 1
    `$timestamp = date_create_from_format('D, d F, Y')` and you'd end up with a valid timestamp, with the proper year. letting php guess works some of the time, but not ALL of the time. – Marc B Mar 13 '13 at 19:56
  • now I see the benefit of it. thank you. – Run Mar 13 '13 at 20:01

2 Answers2

4

Looks like the format isn't correct. It does return the correct year, when you do the following.

$string = "Saturday, 23 March, 2013";
                             ^ //no comma here, should be just 23 March 2013

Everywhere in the supported formats, it is seen that all components of the Date-string and the time-string have the same delimiters separating them.

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • 2
    interestingly, `date('r', strtotime('Saturday, 23 March, 2013'))` does come back with 2013 as expected. must be something odd internally within PHP, because the docs state that date_parse accepts the same formats as strtotime. – Marc B Mar 13 '13 at 19:22
  • @MarcB It is doing something rather peculiar with the above example you mentioned. It seems to put the 2013 in the `HH:MM` field. – Anirudh Ramanathan Mar 13 '13 at 19:27
  • Actually, @Mark B, it's coming back with 2013 because that's the current year. If you do `print(date('r', strtotime('Saturday, 23 March, 2012')))`, it will print **Sat, 23 Mar 2013 20:12:00 -0600**. It's just a side-effect of the current year being 2013. The 2013 are being parsed as the hour and minute. – Blake Schwendiman Mar 13 '13 at 19:29
  • @blake: makes sense. just another reason to avoid strtotime and company like the plague – Marc B Mar 13 '13 at 19:57
0

You might also try strtotime(). It's an amazing function and handles a wide variety of inputs - even relative ones like "3 days ago."

user984869
  • 432
  • 2
  • 8