为什么DateTime::diff方法计算得到的分钟数结果不正确?
问题原因
DateInterval::format() 方法的 %i 格式化参数仅返回时间差中分钟位的独立数值,不会累计小时、天数等更高时间单位对应的分钟数。比如两个时间相差1小时5分钟时,%i只会返回5,而非65,因此无法得到正确的总分钟差值。
修复方案
方案1:通过时间戳直接计算(推荐)
直接将两个时间对象转为时间戳相减,再换算为分钟即可,逻辑更简单不易出错:
$time_now = new DateTime("now",new DateTimeZone("America/New_York")); $future_order_time = new DateTime("7:00 pm",new DateTimeZone("America/New_York")); $diff_minutes = (int)(($future_order_time->getTimestamp() - $time_now->getTimestamp()) / 60); // 若需要忽略时间先后顺序取正数差值,可改为 $diff_minutes = abs($diff_minutes); echo $diff_minutes;
方案2:基于DateInterval手动累加总分钟
如果要沿用diff方法返回的DateInterval对象,需要手动累加天、小时对应的分钟数:
$time_now = new DateTime("now",new DateTimeZone("America/New_York")); $future_order_time = new DateTime("7:00 pm",new DateTimeZone("America/New_York")); $interval = $time_now->diff($future_order_time); $diff_minutes = $interval->days * 24 * 60 + $interval->h * 60 + $interval->i; echo $diff_minutes;
内容的提问来源于stack exchange,提问作者Eldan Shkolnikov
相关产品推荐
相关产品推荐

