时间戳检查是否大于12小时


Timestamp check if older than 12 hours

如何检查时间戳是否大于12小时?

我需要使一个链接工作12小时,之后我需要显示一个错误消息。

$dateFromDatabase = strtotime("2012-12-04 12:05:04");
$dateTwelveHoursAgo = strtotime("-12 hours");
if ($dateFromDatabase >= $dateTwelveHoursAgo) {
    // less than 12 hours ago
}
else {
    // more than 12 hours ago
}

#1。

如果你有TIMESTAMP字段:

timestampField < (CURRENT_TIMESTAMP() - 3600*12)

如果你有DATETIME字段:

datetimeField < DATE_SUB(NOW(), INTERVAL 12 HOUR)

# 2。

$c = new DateTime;
$d = new DateTime('you timestamp or datetime');
if ($c < $d->modify('-12 hour')) { ...

我想你是指unix时间戳。如果是这样,你可以应用简单的数学:

// a unix-timestamp is the time since 1970 in seconds
// 60 seconds = 1 minute, 60 minutes = 1 hour, 12 hours
// so this calculates the current timestamp - 12 hours and checks
// if 12 hours ago the timestamp from your database lay in the future
if ( $timestamp > (time() - 60*60*12) ) {
    // show your link
} else {
    // 12 hours are up
    // give your error message
}

如果你的数据库返回一个格式化的日期(像mysql的时间戳/日期字段类型),你必须使用strtotime()先得到一个unix时间戳

我假设您在下载链接中使用了唯一的密钥。只需在WHERE语句中包含时间戳子句:

<?php
$timestamp = date('Y-m-d H:i:s', strtotime('-12 hours'));
$sql = "SELECT * FROM `links` WHERE `key` = :key AND `created` > :timestamp";
$stmt = $db->prepare($sql);
$stmt->bindParam(':key', $key, PDO::PARAM_STR);
$stmt->bindParam(':timestamp', $timestamp, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetchObject();