PHP date format converting

后端 未结 4 1549
青春惊慌失措
青春惊慌失措 2020-11-29 13:00

Here is what I have:

$dateFormat = \'M d, Y\';
$dateString = \'January 23, 2010\';

What I need is a timestamp of $dateString s

相关标签:
4条回答
  • 2020-11-29 13:16

    As of PHP5.3 you can use the DateTime API

    $dt = date_create_from_format('M d, Y', 'January 23, 2010');
    echo date_timestamp_get($dt);
    

    or with OOP notation

    $dt = DateTime::createFromFormat('M d, Y', 'January 23, 2010');
    echo $dt->getTimestamp();
    

    Note that while DateTime is available in PHP < 5.3, the methods used above are not and while you could simulate ->getTimestamp() with ->format('U'), there is no easy workaround for createFromFormat()

    An alternative would be to use Zend_Date from Zend Framework:

    $date = new Zend_Date('Feb 31, 2007', 'MM.dd.yyyy');
    echo $date->get(Zend_Date::TIMESTAMP);
    
    0 讨论(0)
  • 2020-11-29 13:27

    Use strptime, mktime and strftime:

    $ftime = strptime($dateString, $dateFormat);
    $timestamp = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1,
                        $ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);
    
    echo strftime('Y-m-d', $timestamp);
    

    Please note that strptime is not implemented on Windows platforms.

    Note that the arguments to mktime are somewhat unusual - strptime returns a day of the year (between 0-365, inclusive) rather than a day of the month and a month, so we set the month parameter to mktime to 1, and add 1 to the day of the year. Also, strptime returns years since 1900 for the year value it returns, so we need to add 1900 to the year before passing it through to mktime.

    Also, you might want to check whether $ftime is FALSE before passing it into mktime. strptime returning FALSE denotes that the inputs $dateString is not a valid date format according to $dateFormat.

    0 讨论(0)
  • 2020-11-29 13:30

    Given my understanding of the question and what is available in PHP, you need to relax your expectations somewhere or other.

    A 'simple' solution (which has already been discounted) would be to force using PHP 5.3 and the tools available in it.

    A less simple solution would be to take those additions and port them over to PHP-land (with PHP 4 compatibility, good luck).

    Another route of exploration would be to consider the occasions where strtotime does not work for you and working around those limitations.

    How widely variant are your format strings? It may be possible to come up with a solution mapping format strings to functions/methods (to do that date parsing) providing they're pretty restricted.

    0 讨论(0)
  • 2020-11-29 13:41
    $dateFormat = 'M d, Y'
    $timestamp = strtotime($dateString);
    echo date($dateFormat, $timestamp); 
    

    if i haven't misunderstand your question you can try the code above..

    0 讨论(0)
提交回复
热议问题