开发者

How to create Date object from the string date in Javascript for the first years of A.D?

I have next date string:

"Thu Nov 14 0002 01:01:00 GMT+0200 (GTB Standard Time)"

and I'm trying to convert it to the Date object:

date = new Date("Thu Nov 14 0002 01:01:00 GMT+0200 (GTB Standard Time)")  
=> Invalid Date {}

and it doesn't work. And

date = ne开发者_JS百科w Date("Thu Nov 14 2 01:01:00 GMT+0200 (GTB Standard Time)")  
=> Invalid Date {}

doesn't work too

but

date = new Date("Thu Nov 14 2002 01:01:00 GMT+0200 (GTB Standard Time)")

works

Does anyone know an elegant way to parse it ?


You can set any date. including minutes,hours and milliseconds directly using a timestamp- dates before 1970 are negative integers.

alert(new Date(-62076675540000).toUTCString());

// >> Wed, 13 Nov 0002 23:01:00 GMT

Or you can set the date as a string by replacing the years to make it over 1000,
then subtracting the amount you added  with setFullYear()

var d=new Date("Thu Nov 14 1002 01:01:00 GMT+0200 (GTB Standard Time)")
d.setFullYear(d.getFullYear()-1000)
alert(d.toUTCString())

// >> Wed, 13 Nov 0002 23:01:00 GMT

You can automate a conversion to timestamps-

var s="Thu Nov 14 0002 01:01:00 GMT+0200 (GTB Standard Time)";
var y=s.split(' ')[3], y2=5000+(+y);
var d=new Date(s.replace(y,y2));
d.setFullYear(d.getFullYear()-5000)
var timestamp=+d;
alert(timestamp)
// >> -62076675540000


Javascript dates are based on a count of milliseconds since 1 Jan 1970, 00:00:00.000 UTC. Dates before that are not defined.

You'll have to come up with your own way to represent such dates.

edit — well having said that, Javascript seems willing to represent dates with weirdly large negative offfsets from the epoch; offsets that don't fit in 32 bit integers. I suspect that the root cause of your date is simply that the format it's in upsets the parser. There's supposed to be a comma after the day abbreviation.

Another problem (boy this is way more interesting than I thought) is that in Chrome and Firefox at least any year before 100 is treated as an abbreviation for a year in the 20th century.

edit again — according to the Mozilla docs, a Date can be anything in the range of -100,000,000 days before the epoch to 100,000,000 days after it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜