douzuqin3467 2013-11-06 10:03
浏览 46
已采纳

php DateTime diff仅考虑Y-m-d格式

In mysql db I've a timestamp field (dateexp) defined in my t1 table. with a query I consider only format Y-m-d of timestamp to find records. Use curdate() instead of now()

SELECT * FROM t1 WHERE dateexp < currdate()

I would like to do the same thing with php using DateTime class for find a number of days until a date but I can't understand how I could do it comparing only the Y-m-d format.

I tried in this way but I use Y-m-d H:i:s format.

$row['dateexp'] = "2013-11-10 12:00:00";

$d1 = new DateTime();
$d2 = new DateTime($row['dateexp']);
$interval = $d1->diff($d2);
$days = $interval->format('%r%a');

How could I do this for comparing only Y-m-d? I tried with DateTime::createFromFormat but probably in wrong way..

Thanks

  • 写回答

3条回答 默认 最新

  • dpy15285 2013-11-06 10:51
    关注

    You have several possible ways to do this. First, you can select date string in desired format from DBMS:

    SELECT *, DATE(dateexp) AS date_holder FROM t1 WHERE dateexp < currdate()
    

    and then apply it in your DateTime object:

    $d1 = new DateTime(date('Y-m-d'));
    $d2 = new DateTime($row['date_holder']);
    $interval = $d1->diff($d2);
    $days = $interval->format('%r%a');
    

    Second - you can, as you've mentioned, create DateTime from format:

    $d1 = new DateTime(date('Y-m-d'));
    $d2 = new DateTime(date('Y-m-d', strtotime($row['dateexp'])));
    $interval = $d1->diff($d2);
    $days = $interval->format('%r%a');
    

    -so you'll be able to avoid selection of additional field in DBMS

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

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿