Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

datetime - Why does the month argument range from 0 to 11 in JavaScript's Date constructor?

When initializing a new Date object in JavaScript using the below call, I found out that the month argument counts starting from zero.

new Date(2010, 3, 1);  // that's the 1st April 2010!

Why does the month argument start from 0? On the other hand, the day of the month argument (last one) is a number from 1 to 31. Are there good reasons for this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The real answer to this question, is that it was copied from java.util.Date, which also had this quirk. Proof can be found on Twitter from Brendan Eich - the guy who originally implemented JavaScript:

https://twitter.com/BrendanEich/status/481939099138654209

First Tweet, which says: "In case it helps (it doesn't for most), JS's Date is a copy of Java's JDK1.0 (1995) java.util.Date.  Made it look like Java..."

https://twitter.com/BrendanEich/status/771006397886533632

Second Tweet, which says: "We were under "Make It Look Like Java" mgmt orders, and I had ten days to demo.  No time to invent our own date API or even fix Java's."

Brendan also indicates that it was Ken Smith of Netscape who did the porting from Java.

https://twitter.com/BrendanEich/status/771006208949891072

Third Tweet, which says: "Only Mocha src file I didn't create was mo_date.c: Ken Smith of Netscape helped me translate java.util.Date from Java to C."

This happened in 1995, and JDK 1.0 was in beta. It launched in 1996. In 1997, JDK 1.1 came out which deprecated the vast majority of functions on java.util.Date, moving them over to java.util.Calendar, but even that still had zero-based months. Developers fed-up with this created the Joda-Time library, which ultimately led to java.time package that's baked in to Java 8 (2014).

In short, it took 18 years for Java to get a correctly designed date/time API built-in, but JavaScript is still stuck back in the dark ages. We do indeed have excellent libraries like Luxon Moment.js, date-fns, js-joda, and others. But as of now, there is nothing more than Date built-in to the language. Hopefully this will change in the near future with the TC39 Temporal proposal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...