Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the difference of datetime field and now in PHP?

Tags:

php

datetime

I have a datetime field in my database that contains the following information:

2012-05-03 17:34:01

I want to check the difference between the datetime field and now:

$now = date("Y-m-d H:i:s");

I am attempting to work out how many days have passed between now and the time written to the database field.

How can I achieve this?

like image 239
hairynuggets Avatar asked May 04 '12 11:05

hairynuggets


People also ask

How can I get the difference between two time in PHP?

php $start = strtotime("12:00"); $end = // Run query to get datetime value from db $elapsed = $end - $start; echo date("H:i", $elapsed); ?>

How do you calculate timestamp difference?

Discussion: If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.


2 Answers

Here is the answer :)

$now = new DateTime();
$date = new DateTime("2012-05-03 17:34:01");

echo $date->diff($now)->format("%d days, %h hours and %i minutes");
like image 102
Max M Avatar answered Oct 11 '22 11:10

Max M


$diff = abs(strtotime($date2) - strtotime($date1));
like image 41
swati Avatar answered Oct 11 '22 12:10

swati