Reputation: 35059
I need to translate an integer representing the number of days since 01.01.1601 (as of 6th November 2012: 150422) to a javascript Date
object.
Each year has approximately 365.242199
days, so the calculation should be as follows:
var daysPerYear = 365.242199;
var daysSince = 150422;
var year = 1601 + Math.floor(daysSince / daysPerYear); // correct, gives me 2012
var days = Math.floor(daysSince % daysPerYear); // wrong, gives me 307
Now I create the Date
object:
var date = new Date(year, 0);
date.setDate(days);
The date
now points to 'Fri Nov 02 2012 00:00:00 GMT+0100 (CET)'
which is off by about 4 days.
What is wrong with my calculation? Is there an easier way to obtain the Date
object?
Upvotes: 1
Views: 377
Reputation: 4116
Clone out a copy of OpenCOBOL 1.1, and look through libcob/intrinsic.c for computations.
See cob_intr_date_of_integer in particular.
For an SVN readonly checkout
svn checkout svn://svn.code.sf.net/p/open-cobol/code/trunk open-cobol-code
or browse to
http://sourceforge.net/projects/open-cobol/files/open-cobol/1.1/open-cobol-1.1.tar.gz/download
Upvotes: 1
Reputation: 9211
JavaScript dates revolve from midnight on 1st January, 1970. If you do new Data().getTime()
, for example, you'll be returned the number of milliseconds from that point. Therefore, to convert your dates from 1st January, 1601, you need to calculate the exact number of milliseconds between 1/1/1601 and 1/1/1970 and take the difference from your date (also converted into milliseconds).
This way, all you are doing is adding numbers together and won't suffer from any floating point inaccuracies or error from your approximations.
Upvotes: 0