Search code examples
phparraysregexdatetimedate-parsing

Parse datetime string into an array of its individual units


I have looked at several of the other regular expressions questions here and on other message boards. I am beating my head against the wall because I just can't seem to wrap my head around this. (or regular expressions in general)

I am pulling a time stamp from a MYSQL database. This is automatically generated, so it is formatted normally: 2011-12-17 21:30:56

I want to break this up into an array without having to use multiple explodes. I am assuming preg_split() is the answer here. If you have a better idea, I am all ears (though I feel like I need to figure out how to use regular expressions at some point anyway.)

In any case, I am trying to split this up at each "-" ":" and " ". After a bit of reading it seems like a character class is the answer, here is my code, that is simply not working:

$date_arr = preg_split("/ [- :] /", $order['order_date']);

This is outputting: Array ( [0] => 2011-12-17 21:30:56 )

Where am I going wrong?


Solution

  • The reason your preg_split fails is because of the spaces surrounding [- :].

    As it's currently written in will only split on " - ", "   " and " : ".

    $date_arr = preg_split("/ [- :] /", ... ); // original
    $date_arr = preg_split("/[- :]/", ...);    // fixed
    

    Instead of using functions such as explode and preg_split to split your string, use strtotime and getdate:

    print_r (
      getdate (strtotime ("2011-12-17 21:30:56"))
    );
    

    ...

    Array
    (
        [seconds] => 56
        [minutes] => 30
        [hours] => 21
        [mday] => 17
        [wday] => 6
        [mon] => 12
        [year] => 2011
        [yday] => 350
        [weekday] => Saturday
        [month] => December
        [0] => 1324153856
    )