Search code examples
phpstringunix-timestamp

Convert String To date in PHP


How can I convert this string 05/Feb/2010:14:00:01 to unixtime ?


Solution

  • For PHP 5.3 this should work. You may need to fiddle with passing $dateInfo['is_dst'], wasn't working for me anyhow.

    $date = '05/Feb/2010:14:00:01';
    $dateInfo = date_parse_from_format('d/M/Y:H:i:s', $date);
    $unixTimestamp = mktime(
        $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
        $dateInfo['month'], $dateInfo['day'], $dateInfo['year'],
        $dateInfo['is_dst']
    );
    

    Versions prior, this should work.

    $date = '05/Feb/2010:14:00:01';
    $format = '@^(?P<day>\d{2})/(?P<month>[A-Z][a-z]{2})/(?P<year>\d{4}):(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})$@';
    preg_match($format, $date, $dateInfo);
    $unixTimestamp = mktime(
        $dateInfo['hour'], $dateInfo['minute'], $dateInfo['second'],
        date('n', strtotime($dateInfo['month'])), $dateInfo['day'], $dateInfo['year'],
        date('I')
    );
    

    You may not like regular expressions. You could annotate it, of course, but not everyone likes that either. So, this is an alternative.

    $day = $date[0].$date[1];
    $month = date('n', strtotime($date[3].$date[4].$date[5]));
    $year = $date[7].$date[8].$date[9].$date[10];
    $hour = $date[12].$date[13];
    $minute = $date[15].$date[16];
    $second = $date[18].$date[19];
    

    Or substr, or explode, whatever you wish to parse that string.