How to convert date to timestamp in PHP?

前端 未结 19 2541
暗喜
暗喜 2020-11-22 05:38

How do I get timestamp from e.g. 22-09-2008?

19条回答
  •  生来不讨喜
    2020-11-22 06:13

    With DateTime API:

    $dateTime = new DateTime('2008-09-22'); 
    echo $dateTime->format('U'); 
    
    // or 
    
    $date = new DateTime('2008-09-22');
    echo $date->getTimestamp();
    

    The same with the procedural API:

    $date = date_create('2008-09-22');
    echo date_format($date, 'U');
    
    // or
    
    $date = date_create('2008-09-22');
    echo date_timestamp_get($date);
    

    If the above fails because you are using a unsupported format, you can use

    $date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
    echo $dateTime->format('U'); 
    
    // or
    
    $date = date_parse_from_format('!d-m-Y', '22-09-2008');
    echo date_format($date, 'U');
    

    Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.

    Yet another alternative is to use the IntlDateFormatter API:

    $formatter = new IntlDateFormatter(
        'en_US',
        IntlDateFormatter::FULL,
        IntlDateFormatter::FULL,
        'GMT',
        IntlDateFormatter::GREGORIAN,
        'dd-MM-yyyy'
    );
    echo $formatter->parse('22-09-2008');
    

    Unless you are working with localized date strings, the easier choice is likely DateTime.

提交回复
热议问题