views:

1047

answers:

5

At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion:

function daysToTimestamp(days) {
    return Math.round(+days * 86400);
}

By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why?

+2  A: 

It is because it is neither a linear representation of time nor a true representation of UTC (though it is frequently mistaken for both) as the times it represents are UTC but it has no way of representing UTC leap seconds

http://en.wikipedia.org/wiki/Unix_time

pfranza
What good is it then? :-)
Andrew Hedges
+4  A: 

1199059200 represents December 31 2007 in UTC. Sample Python session:

>>> import time
>>> time.gmtime(1199059200)
(2007, 12, 31, 0, 0, 0, 0, 365, 0)

Remember that all time_t values are against UTC. :-) You have to adjust accordingly to your timezone.

Edit: Since you and I are both in New Zealand, here's how you might have got the 1199098800 value:

>>> time.localtime(1199098800)
(2008, 1, 1, 0, 0, 0, 1, 1, 1)

This is so because in New Year (summer in New Zealand), the timezone here is +1300. Do the maths and see. :-)

For January 1 2008 in UTC, add 86400 to 1199059200, and get 1199145600.

>>> time.gmtime(1199145600)
(2008, 1, 1, 0, 0, 0, 1, 1, 0)
Chris Jester-Young
+1  A: 

Unix times (time_t) are represented in seconds since Jan 1, 1970 not milliseconds.

I imagine what you are seeing is a difference in timezone. The delta you have is 11 hours, how are you getting the expected value?

Rob Walker
I won't speak for the OP, but chances are good that he's using mktime for that purpose. There's another thread about implementing a mkgmtime on top of mktime, but it's ugly: http://stackoverflow.com/questions/130074
Chris Jester-Young
A: 

You should multiply by 86400000

1 day = 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 86400000

Ahmad
A: 

Because 1199098800/86400 = 13878.4583333333333 (with the 3 repeating forever), not 13878.0. It gets rounded to 13878.0 since it's being stored as an integer. If you want to see the difference it makes, try this: .4583333333333*86400 = 39599.99999999712. Even that makes it slightly incorrect, but this is where the discrepancy comes from, as 1199098800-1199059200=35600.

Dave