Tips for working with Pre-1000 A.D. Dates in JavaS

2020-06-11 14:51发布

I'm curious if anyone has any good solutions for accurately building dates prior to the year 1000 A.D. - particularly the years 1 - 100 AD.

For example, if I want to build a date for the start of the 1st millenium, I can't just do...

new Date(Date.UTC(1,0,1,0,0,0,0));

because it tries to be "smart" and assume that 1 is 1901, which gives me...

Sun Dec 31 1900 18:00:00 GMT-0600 (CST)

The same thing goes for the year 99...

new Date(Date.UTC(99,0,1,0,0,0,0));

which becomes

Thu Dec 31 1998 18:00:00 GMT-0600 (CST)

Thoughts?

6条回答
我想做一个坏孩纸
2楼-- · 2020-06-11 15:33

Others have provided hints at a fix. The javascript date object was copied from Java, so has all its bugs too. There is not much point to Gregorian dates before 1582 anyway since before that various other calendars were in use.

查看更多
Ridiculous、
3楼-- · 2020-06-11 15:40

Here is the basic solution I came up with. If a date is prior to year 1000, I just add a 1000 to it while constructing the date, then use setUTCFullYear() afterwards.

if (year >= 0 && year < 1000) { 
  var d = new Date(Date.UTC(year + 1000,mon,day,hour,min,sec,0));
  d.setUTCFullYear(d.getFullYear() - 1000); 
  return d; 
}

1000 may be overkill since I was only having problems with pre-100 dates... but, whatever.

查看更多
孤傲高冷的网名
4楼-- · 2020-06-11 15:48

Have you tried using the setUTC... functions on a date object after its creation?

setUTCDate()
setUTCFullYear()
setUTCMonth()
setUTCHours()
setUTCMinutes()
setUTCSeconds()
查看更多
Animai°情兽
5楼-- · 2020-06-11 15:50

i prefer:

var d = new Date(Date.UTC(year, month, day, hour, min, sec, 0));
d.setUTCFullYear(year);

this always works for all supported year values.

the setUTCFullYear() call fixes JavaScript's intentional bug if you ask me.

查看更多
Ridiculous、
6楼-- · 2020-06-11 15:50

It's exactly what Date.UTC and the Date constructor function (called with numbers as arguments) are supposed to do. A simple workaround is to use Date.parse, which will not apply any corrections

new Date(Date.parse('0001-01-04'));
new Date(Date.parse('0001-01-04T18:00:00Z'));
查看更多
家丑人穷心不美
7楼-- · 2020-06-11 15:58

Make some arbitrary date d and call d.setUTCFullYear(myDate). This seems to be working for me in Chrome's console.

查看更多
登录 后发表回答