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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献