简体   繁体   中英

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 .

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 % .

Use this simple PHP code:

$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.

And for your information, the date formats and inteval formats can be found in these links. Both of them are php manuals.

Use DATEDIFF(datepart,startdate,enddate) If it's generic database query. But use date_diff if it's PHP operation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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