如何比较datetime和时间在php


How to compare datetime and time in phpmysql

只有一个问题:是否可以比较日期时间格式和时间格式?

我有表employee_attendance(日期时间类型)和表employee_schedule(时间类型),这是为了确定员工是否迟到。

请查看我的代码。

$CheckInNew  = strtotime('2013-06-05 08:47:53');
$OnDutyTimeNew   = strtotime('08:00:00');
if($CheckIn > $OnDutyTimeNew){
// confirming that the employee is late
} else {
// confirming that the employee is NOT late
}

任何想法?

谢谢

try this:

$CheckInNew  = date('B',strtotime('2013-06-05 08:47:53'));
$OnDutyTimeNew   = date('B',strtotime('08:00:00'));
if ($CheckInNew > $OnDutyTimeNew)
    echo 'late!';
else
    echo 'early!';

我用be作为Internet Swatch Time的关键字。更多信息请访问

链接

更新:PHPFiddle

为什么不将时间解析为时间戳,然后使用strtotime()函数进行比较

假设您想比较与CheckInDateOnly日期相同的日期

您可以通过将datetime仅转换为日期,并将其添加到OnDutyTime变量中来做到这一点。

$checkInDateTime = strtotime('2013-06-05 08:47:53');
$checkInDateOnly = date("Y-m-d", $checkInDateTime);
$OnDutyTimeNewWithSameDateAsCheckIn = strtotime($checkInDateOnly . '08:00:00');
echo ($checkInDateTime > $OnDutyTimeNewWithSameDateAsCheckIn ? "Late" : "Early");

使用示例:PHPFiddle

由于日期格式包含前导零,因此您可以简单地使用纯字符串compare来比较日期。

$checkInDateTime  = '2013-06-05 08:47:53';
$dutyTime = '08:00:00';
if (substr($checkInDateTime, -8) > $dutyTime) {
    echo "Late";
} else {
    echo "Early";
}

通常,一天分为1440分钟。Swatch Internet time将一天分成1000拍。因此1拍= 1.44分钟。使用Swatch Internet time来比较正常时间是不准确的,因为它不包括秒,并且有分钟误差(至少这是我所相信的)。

您可以在SQL中这样做:

-- checkin is the column with their checkin time
-- scheduled is the column with their scheduled time
SELECT
    TIMEDIFF(TIME(checkin), scheduled) AS diff

如果diff为阴性,则他们准时到达。如果是正数,则为延迟

参考

  • TIMEDIFF()
  • TIME()