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


当前回答

下面是一个非常简单而有效的解决方案,使用split和mtime函数:

$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date); 

//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);

这对我来说就像魔法一样。

其他回答

请注意时间/区域,如果你设置它保存在数据库中的日期,因为我得到了一个问题,当我从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)

考虑到函数strptime()不适用于Windows, strtotime()可能会返回意外的结果,我建议使用date_parse_from_format():

$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);

使用mktime:

list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
<?php echo date('U') ?>

如果你愿意,把它放在一个MySQL输入类型时间戳中。上面的代码运行得很好(仅适用于PHP 5或更高版本):

<?php $timestamp_for_mysql = date('c') ?>

还有strptime(),它只需要一种格式:

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

警告:

Windows系统不支持该功能 该函数在PHP 8.1.0中已弃用。非常不鼓励依赖这个函数。