-1

I have this code to get the difference between two timestamps one in the past and one is NOW and i want to have the difference in seconds and minutes and hours and days but i get a wrong values each time . I need to know if I am dividing on right values:

<?php
$timestamp = '2013-11-16 16:26:30';
$post_date = strtotime($timestamp);
//echo $post_date;echo '</br>';
date_default_timezone_set('Asia/Istanbul');
$now = new DateTime();
$now_date =  $now->getTimestamp();
//echo $now_date;
$timediff = $now_date - $post_date;

echo floor($timediff/1000);echo' Seconds';
echo floor($timediff/60);echo' Minutes';
echo floor(($timediff/60)/60);echo' Hours';
echo floor(((($timediff/60)/60)/24));echo' Days';

?>
Basel
  • 1,305
  • 7
  • 25
  • 34
  • 1
    You should set your timezone _before_ you start manipulating dates or you'll get errors as the timezone changes. You can set the timezone after if that's what you mean to do, but be aware of the implications. –  Nov 18 '13 at 06:59

1 Answers1

-1

This will work for you.

$timestamp = '2013-11-17 00:00:00';
$post_date = strtotime($timestamp);

date_default_timezone_set('Asia/Istanbul');
$now = new DateTime();
$now_date =  $now->getTimestamp();
//echo $now_date;
$timediff = $now_date - $post_date;

echo floor($timediff%60).' Seconds<br>';
echo floor($timediff/60 % 60).' Minutes<br>';
echo floor(($timediff/3600 % 24)).' Hours<br>';
echo floor(((($timediff/60)/60)/24)).' Days';
  • this work for me thanks but on edit for that answer is to place the date_default_timezone_set before anything in the code – Basel Nov 18 '13 at 07:38
  • how to calculate the months and years? – Basel Nov 18 '13 at 07:44
  • For year and month you can use the following code. `$years = floor($timediff / (365*60*60*24));` for year,`floor(($timediff - $years * 365*60*60*24) / (30*60*60*24));` for months – Uphar Srivastava Nov 18 '13 at 09:00
  • Calculation difference this way is just wrong because not all years have 365 days and not all months have 30 days, and this just calls for wrong output... If you are already using DateTime class, then you can use method `diff()`... – Glavić Nov 18 '13 at 11:22
  • yes Glavic you are right. there must be a check for a leap year. – Uphar Srivastava Nov 20 '13 at 05:22