views:

373

answers:

5

I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).

Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates older than 1901 to easily subtract the present timestamp from etc.. So how do I do what I want to do?

+4  A: 

In python, there's the datetime module. Specifically, the date class will help.

from datetime import date
print date(1850, 1, 1).weekday()  # 1, which is Tuesday 
# (Mon is 0)

Edit

Or, to your specific problem, working with timedelta will help out.

from datetime import datetime
td = datetime.now() - datetime(1850, 1, 1)
print (86400*td.days)+td.seconds  # seconds since then till now
nilamo
+3  A: 

The portable, language-agnostic approach:

Step 1. Count the number of seconds between 01/01/1850 00:00 and 01/01/1901 00:00. Save this number somewhere (call it M)

Step 2. Use available language functionality to count the number of seconds between 01/01/1901 00:00 and whatever other date and time you want.

Step 3. Return the result from Step 2 + M. Remember to cast the result as a long integer if necessary.

mobrule
taht will not work. The number of seconds between 01/01/1850 and 01/01/1901 will depend on the exact local of the point at which the time is taken. See: http://wikipedia/wiki/Gregorian_calendar for information about the adaption of the Calendar.
Martin York
+1  A: 

Under WIN32, you can use SystemTimeToFileTime.

FILETIME is a 64-bit unsigned integer that counts the number of 100-nanosecond intervals since January 1, 1601 (UTC).

You can convert two timestamps to FILETIME. You can convert it to ULARGE_INTEGER (t.dwLowDateTime + t.dwHighDateTime << 32), and do regular arithmetics to measure the interval.

Lior Kogan
A: 

Why not use Date objects instead of integers, at least to get a starting point.

function secondsSince(D){
 D= new Date(Date.parse(D));
 D.setUTCHours(0,0,0,0); 
 return Math.floor((new Date()-D)/1000);
}

//test with a date

var daystring='Jan 1, 1850', ss= secondsSince(daystring), diff= ss/(60*60*24*365.25);

alert('It has been '+ ss + ' seconds since 00:00:00 (GMT) on ' + daystring + '\n\nThat is about '+diff.toFixed(2)+' years.');

kennebec
A: 

The egenix datetime is also worth looking at http://www.egenix.com/products/python/mxBase/mxDateTime/

gnibbler