我有从MySQL返回的记录有日期时间字段。我想要做的是采取这个值,看看它是否比24小时更老,我认为使用PHP的时间()来获得当前时间。检查mySql的日期时间是否比php早1天()
此刻,如果我赞同出来,我得到:
1276954824 this is php's time()
2010-06-19 09:39:23 this is the MySQL datetime
我相信上面一个是UNIX时间?一直玩strtotime但没有太大的成功..
任何帮助欢迎!
我有从MySQL返回的记录有日期时间字段。我想要做的是采取这个值,看看它是否比24小时更老,我认为使用PHP的时间()来获得当前时间。检查mySql的日期时间是否比php早1天()
此刻,如果我赞同出来,我得到:
1276954824 this is php's time()
2010-06-19 09:39:23 this is the MySQL datetime
我相信上面一个是UNIX时间?一直玩strtotime但没有太大的成功..
任何帮助欢迎!
没有成功?
echo strtotime("2010-06-19 09:39:23");
给我
1276940363
(mktime(9, 39, 23, 6, 19, 2010)
给出了同样的时间,所以解析正常工作)
要获得秒的差异,您可以。减去时间戳,例如
$diff = time() - strtotime("2010-06-19 09:39:23");
如果差异大于86400(60 * 60 * 24)秒,那么时间戳相隔超过一天:
if(time() - strtotime("2010-06-19 09:39:23") > 60*60*24) {
// timestamp is older than one day
}
你为什么要混合PHP时间和MySQL时间?
而是直接做比较,在MySQL:
要获得MySQL的当前日期/时间使用NOW()
功能。您可以比较,例如,2010-06-19 09:39:23' < DATE_SUB(NOW(), INTERVAL 1 DAY)
这将检查给定日期(推测在列中)是否早于24小时。
如果绝对有必要将MySQL时间戳转换为UNIX时间戳,那么可以使用MySQL的UNIX_TIMESTAMP()
函数来完成此操作。
我会做,但目前还没有访问查询,所以这就是为什么我需要做它与返回的值。 – 2010-06-19 14:09:41
你也可以这样做:
SELECT * FROM my_table WHERE timestamp < NOW() - INTERVAL 1 DAY;
DATE_SUB(CURDATE(),INTERVAL 1天)是正确的方法 – 2013-11-08 09:50:05
@Zahid:我发布的解决方案有什么问题? – 2013-11-08 23:46:44
我写了一个函数,通过该函数可以确定第一个给定日期是一天还是n天大于或小于第二个给定日期。
$date1 = "2013/03/01";
$date2 = "2013/03/01";
$sign = "-";
$diff = 1;
$result = isDaysSmallerBigger($date1, $date2, $sign, $diff);
var_dump($result);
/**
* Note: this function is only supported in php 5.3 or above
* 1. If $date1 - $date2 = $sign $diff days, return true;
* 2. If $date1 equals $date2 and $diff euqals 0, whether $sign is "+" or "-", return true
* 3. Else return false;
* @param unknown_type $date1
* @param unknown_type $date2
* @param string $sign: "-": $date1 < $date2; "+": $date1 > $date2;
* Besides if $diff is 0, then both "-" and "+" means $date1 === $date2;
* @param integer $diff: date difference between two given dates
*/
function isDaysSmallerBigger($date1, $date2, $sign, $diff) {
$dateTime1 = new DateTime($date1);
$dateTime2 = new DateTime($date2);
$interval = $dateTime2->diff($dateTime1);
$dayDiff = $interval->format('%a');
$diffSign = $interval->format('%R');
if((int)$dayDiff === (int)$diff) {
// Correct date difference
if((int)$diff !== 0) {
// Day difference is not 0
if($diffSign === $sign) {
return true;
} else {
return false;
}
} else if((int)$diff === 0) {
// Day difference is 0, then both given "+" and "-" return true
return true;
}
} else {
// Incorrect date difference
return false;
}
}
非常感谢,今天我的头似乎没有被正确地拧上! – 2010-06-19 14:08:47