How to convert date to timestamp in PHP?

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

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

19条回答
  •  孤独总比滥情好
    2020-11-22 06:21


    This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.

    If you don't care about timezone, or want to use the time zone your server uses:

    $d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
    if ($d === false) {
        die("Incorrect date string");
    } else {
        echo $d->getTimestamp();
    }
    

    1222093324 (This will differ depending on your server time zone...)


    If you want to specify in which time zone, here EST. (Same as New York.)

    $d = DateTime::createFromFormat(
        'd-m-Y H:i:s',
        '22-09-2008 00:00:00',
        new DateTimeZone('EST')
    );
    
    if ($d === false) {
        die("Incorrect date string");
    } else {
        echo $d->getTimestamp();
    }
    

    1222093305


    Or if you want to use UTC. (Same as "GMT".)

    $d = DateTime::createFromFormat(
        'd-m-Y H:i:s',
        '22-09-2008 00:00:00',
        new DateTimeZone('UTC')
    );
    
    if ($d === false) {
        die("Incorrect date string");
    } else {
        echo $d->getTimestamp();
    }
    

    1222093289


    Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.

提交回复
热议问题