Jump to content

Damn timestamps and dates! Wheres the extra 70 years coming from!?


HughbertD

Recommended Posts

I have done a calculation of the differnce in time between two timestamps like so,

 


$start = strtotime($row["dateTime"]);
$end = strtotime($row["dateTimeFin"]);

$result = ($end - $start);

$conv=gmdate("m \m\o\\n\\t\h\s d \d\a\y\s H \h\o\u\\r\s\ i \m\i\\n\s\ s \s\e\c\s",$result);		

echo ($conv);

 

I have noticed however that there is always 1 extra day, 1 extra month and 70 years in the result.

 

I only want the days, hours, minutes of the difference, but I tried taking off 3600*24 for the extra day this works for results of more than one day, but if the time difference is less than a day, it displays 31 days.

 

I don't want to use a function to do this.

 

If anyone can help I would appreciate it massively

Hi, I believe I already solved this in a previous thread started by you.

 

I subtract 1970 from the years and 1 from the months and days, to compensate for the Unix Epoch (1970-01-01 00:00:00 GMT). Seems like that's the source of your problem too!

I gave it a go, it was 6 years out (!)

 

I sent you a PM btw, just so you know. I simply don't understand why counting the number of seconds from 1970 would make the dates do this.

 

Is it the conversion back from the timestamp which is the problem?

 

 

 

 

 

I will try to elaborate on the epoch mystery here, for everyone to see.

 

A Unix timestamp (strtotime() creates this) is the number of seconds elapsed from the Unix epoch to a given time. An epoch is a reference date/time, and the Unix epoch were at 1970-01-01 00:00:00 UTC (this is a tricky definition, since UTC did not exist back then, read here). So when you find the difference in seconds, between two dates (your $result), and uses this span as a timestamp (inside your gmdate() function), the output will be the Unix epoch plus these seconds. And that's why we'll have an extra 1970 years, 1 month and 1 day.

Actually, we're making a 'mistake' when we use the time difference as a timestamp, because it's not. But that can be corrected by subtracting the Unix epoch, like I did in the function in this thread.

 

We should be able to subtract the Unix epoch in your example too, just give me a minute..

I think this should work. I've divided your code, and subtracted 1 day from the actual output of days (like in my function):

 

<?php
$start = strtotime($row["dateTime"]);
$end = strtotime($row["dateTimeFin"]);

$result = ($end - $start);

$conv=(gmdate('d', $result) - 1).' days, '.gmdate('H', $result).' hours and '.gmdate('i', $result).' minutes.';

echo ($conv);
//x days, x hours and x minutes.
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.