Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two timestamp variable in php [duplicate]

Tags:

php

I have two timestamps let us say

 $end_date =  2014-09-09 15:03:10 and now date 
 date_default_timezone_set('Asia/Calcutta'); 
 $now = date('Y-m-d H:i:s');

I want to calculate number of days remaining .Suppose if that particular date crosses now date and it should display remaining days with -ve value.

I am using the following code

$remaining_days =strtotime($end_date) - strtotime($now) ;
$Result_days = floor($remaining_days /86400);
echo $remaining_days.'   '.$Result_days.'<br/>' 

Problem is that if the end date = today's date it is displaying -1 . I want to calculate based on time and display remaining days and hours. Please help me to find out the solution.

like image 996
Akshobhya Avatar asked Sep 16 '26 08:09

Akshobhya


1 Answers

Try this:

<?php
$end_date =  "2014-10-09 15:03:10";
date_default_timezone_set('Asia/Calcutta'); 
$now = date('Y-m-d H:i:s');

$diff = strtotime($now) - strtotime($end_date);
$fullDays    = floor($diff/(60*60*24));   
$fullHours   = floor(($diff-($fullDays*60*60*24))/(60*60));   
$fullMinutes = floor(($diff-($fullDays*60*60*24)-($fullHours*60*60))/60);      
echo "Difference is $fullDays days, $fullHours hours and $fullMinutes minutes.";


Output:

Difference is -30 days, 0 hours and 39 minutes.


Demo:

http://3v4l.org/3auqe


Edit (using DATE OBJECT):

<?php

// Example 1
$end_date =  "2014-09-11 20:35:10";
date_default_timezone_set('Asia/Calcutta'); 
$now = date('Y-m-d H:i:s');

$date1=date_create($now);
$date2=date_create($end_date);
$diff=date_diff($date1,$date2,FALSE);
echo $diff->format("%R%d days, %h hours, %m minutes, %s seconds").PHP_EOL;    
//Output:
+2 days, 3 hours, 0 minutes, 44 seconds


// Example 2
$end_date =  "2014-09-08 20:35:10";
date_default_timezone_set('Asia/Calcutta'); 
$now = date('Y-m-d H:i:s');

$date1=date_create($now);
$date2=date_create($end_date);
$diff=date_diff($date1,$date2,FALSE);
echo $diff->format("%R%d days, %h hours, %m minutes, %s seconds").PHP_EOL;    
//Output:
-0 days, 20 hours, 0 minutes, 16 seconds


Demo:

http://3v4l.org/dPSgX#vhhvm-320

like image 183
Parag Tyagi Avatar answered Sep 18 '26 23:09

Parag Tyagi