简体   繁体   English

PHP中数据库中两个日期之间的差异

[英]Difference between two dates from database in php

Dates are stored in the database in this format 日期以这种格式存储在数据库中

month/day/year - hour:minute AM/PM

Example: 例:

10/06/2014 - 07:25 AM
10/08/2014 - 09:30 AM

I want to find the difference between the dates in x days y hours z minutes . 我想找出x天y小时z分钟中的日期之间的差异。

The date must be first formatted into a php date by using the function date_create_from_format() and the difference is found using the object oriented function $interval->format() with the formats specified with % . 必须先使用date_create_from_format()函数将日期格式化为php日期,然后使用面向对象的函数$interval->format()使用%指定的格式来查找日期差异。

Use this simple PHP code: 使用以下简单的PHP代码:

$format = "m/d/Y - h:i A";
$date1 = "10/06/2014 - 07:25 AM";
$date2 = "10/08/2014 - 09:30 AM";
$date1 = date_create_from_format($format, $date1);
$date2 = date_create_from_format($format, $date2);
$interval = date_diff($date1, $date2);
echo $interval->format('%d days %h hours %i minutes');

This will give you are difference in dates in x days y hours z minutes as you want it to be. 这将为您提供您希望的x天y小时z分钟的日期差。

And for your information, the date formats and inteval formats can be found in these links. 并且,您可以在这些链接中找到日期格式间隔格式 ,以供参考。 Both of them are php manuals. 它们都是php手册。

Use DATEDIFF(datepart,startdate,enddate) If it's generic database query. 如果是通用数据库查询DATEDIFF(datepart,startdate,enddate)请使用DATEDIFF(datepart,startdate,enddate) But use date_diff if it's PHP operation. 但是,如果它是PHP操作,请使用date_diff。

In the case of your question, just put 就您的问题而言,

DATEDIFF(m dd hh, "10/06/2014 -07:25AM", "10/08/2014 - 09:30 AM")

For a general database query 对于常规数据库查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM