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


当前回答

<?php echo date('U') ?>

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

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

其他回答

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

下面是一个非常简单而有效的解决方案,使用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);

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

<?php echo date('U') ?>

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

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

如果你想确定一个日期是否被解析成你想要的,你可以使用DateTime::createFromFormat():

$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
    die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22

在这种情况下很明显,但是例如03-04-2008可能是4月3日或3月4日,这取决于你来自哪里:)

这个方法在Windows和Unix上都可以工作,并且是时区感知的,如果您使用日期,这可能是您想要的。

如果你不关心时区,或者想使用你的服务器使用的时区:

$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(这将取决于您的服务器时区…)

如果要指定在哪个时区,请在这里指定EST(与纽约相同)。

$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

或者如果你想使用UTC。(与“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

无论如何,在将字符串解析为结构化数据时,严格总是一个好的起点。这样可以省去将来调试的麻烦。因此,我建议始终指定日期格式。