如何检查时间戳是否超过12小时?
我需要让链接工作12个小时,之后我需要显示错误信息。
答案 0 :(得分:29)
$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 :(得分:4)
<强>#1。在数据库中进行比较:
如果你有 TIMESTAMP 字段:
timestampField < (CURRENT_TIMESTAMP() - 3600*12)
如果您有 DATETIME 字段:
datetimeField < DATE_SUB(NOW(), INTERVAL 12 HOUR)
<强>#2。用PHP进行比较:
$c = new DateTime;
$d = new DateTime('you timestamp or datetime');
if ($c < $d->modify('-12 hour')) { ...
答案 2 :(得分:1)
我假设您在下载链接中使用了一个唯一的密钥。只需在WHERE
语句中包含timestamp子句:
<?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();
答案 3 :(得分:0)
我猜你的意思是unix-timestamp。如果是这样,你可以应用简单的数学运算:
// 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时间戳。