How to convert date to timestamp in PHP?

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

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

19条回答
  •  醉梦人生
    2020-11-22 06:24

    Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp using strtotime. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.

    Please see this example: https://3v4l.org/BRlmV

    function getthistime($type, $modify = null) {
        $now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));
        if($modify) {
            $now->modify($modify);
        }
        if(!isset($type) || $type == 'datetime') {
            return $now->format('Y-m-d H:i:s');
        }
        if($type == 'time') {
            return $now->format('H:i:s');
        }
        if($type == 'timestamp') {
            return $now->getTimestamp();
        }
    }
    function timestampfromdate($date) {
        return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();
    }
    
    echo getthistime('timestamp')."--".
        timestampfromdate(getthistime('datetime'))."--".
        strtotime(getthistime('datetime'));
    
    //getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)
    //getthistime('timestamp') == strtotime(getthistime('datetime')) (false)
    

提交回复
热议问题