duandu8892 2013-04-02 09:23
浏览 68
已采纳

Php减去两个日期,不同的日期返回错误的结果

I am trying to subtract two dates using php. Dateone is stored in the database while datetwo is the current date. Now, i have this strange scenario: Dateone is 23-03-13 Date two is 02-04-13

Using different subtraction methods, give different results.

Method One - Returns -21

$sqldate ="SELECT exam_date FROM exam_table";
$fetchdate = mysql_query($sqldate);
$rowdate = mysql_fetch_array($fetchdate);
//Fetch the date stored in the database
$dateone = $rowdate['exam_date'];
//Calculate the current date today
$datetwo =date('d-m-y');
//Calculate the diff between the two dates
$datediff = $datetwo-$dateone;

In this case, $datediff returns -21

Method Two - Returns -7639

$sqldate ="SELECT exam_date FROM exam_table";
$fetchdate = mysql_query($sqldate);
$rowdate = mysql_fetch_array($fetchdate);
//Fetch the date stored in the database
$dateone = $rowdate['exam_date'];
//Calculate the current date
$datetwo =date('d-m-y');
//Calculate the diff between the two dates
$datetime1 = strtotime("$dateone");
$datetime2 = strtotime("$datetwo");
//seconds between the two times
$secs = $datetime2 - $datetime1;
$days = $secs / 86400;

In this scenario, $days returns -7639

  • 写回答

5条回答 默认 最新

  • doudou8783 2013-04-02 09:48
    关注

    Yeah issue is because your date format is not standard to get difference. You need to inform your current format to date & convert it to standard one to get correct difference.

    $datetime1 = DateTime::createFromFormat('d-m-Y', '23-03-13'); #In you case it is considering 13-03-2023
    $datetime1->format('d-m-YY');
    $datetime2 = DateTime::createFromFormat('d-m-Y', '02-04-13'); #In you case it is considering 13-04-2002
    $datetime2->format('d-m-YY');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days'); #output +10 days
    

    CodeViper Demo.

    Note: PHP version should be >= 5.3.0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题