如何从例如22-09-2008中获取时间戳?


当前回答

请注意时间/区域,如果你设置它保存在数据库中的日期,因为我得到了一个问题,当我从mysql的日期转换为时间戳使用strtotime比较。在将日期转换为时间戳之前,必须使用完全相同的时间/区域,否则,strtotime()将使用默认的服务器时区。

请看这个例子: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)

其他回答

使用strtotime()函数,您可以轻松地将日期转换为时间戳

<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');

//define date and time
$date = date("d M Y H:i:s");

// output
echo strtotime($date);
?> 

更多信息:http://php.net/manual/en/function.strtotime.php

在线转换工具:http://freeonlinetools24.com/

如果您知道格式,请使用strptime,因为strtotime会对格式进行猜测,这可能并不总是正确的。由于strptime没有在Windows中实现,所以有一个自定义函数

http://nl3.php.net/manual/en/function.strptime.php#86572

记住,返回值tm_year来自1900!tm_month是0-11

例子:

$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)

使用mktime:

list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);

小心使用像strtotime()这样试图“猜测”您的意思的函数(它当然不会猜测,规则在这里)。

事实上,22-09-2008将被解析为2008年9月22日,因为这是唯一合理的事情。

08-09-2008将如何解析?可能是2008年8月9日。

那2008-09-50呢?某些版本的PHP将此解析为20 October 2008。

所以,如果你确定输入的是DD-MM-YYYY格式,最好使用@Armin Ronacher提供的解决方案。

使用PHP函数strtotime()

echo strtotime('2019/06/06');

date -格式化本地时间/日期