donglin6109 2017-03-10 21:45
浏览 38
已采纳

减去时间PHP

I am having trouble with subtracting times in PHP.

My times are:

$row['exp'] = 2017-03-31

and date('Y-m-d') = 2017-03-10 (today)

$datetime1 = strtotime($row['exp']);
$datetime2 = strtotime(date('Y-m-d'));
$secs = $datetime1 - $datetime2;// == <seconds between the two times>
$days = $secs / 86400;
echo $days;

My result is:

36520.958333333333

  • 写回答

1条回答 默认 最新

  • douyujun0152 2017-03-10 21:54
    关注

    Use the PHP DateTime class instead, it has built in functions, such as DateTime::diff, which seems to be what you're looking for. The DateTime objects are much easier to work with too.

    $today = new DateTime('today');
    $date = new DateTime("2017-03-31");
    
    echo $today->diff($date)->d; // 21
    

    Just pass your $row['exp'] as the parameter of $date instead, so you get

    $date = new DateTime($row['exp']);
    

    Although, I can't reproduce your issue with the given input you have, this live demo outputs "20.958333333333" (which is about right, you just need to ceil() it).

    Live demo

    References

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?