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
207 views
in Technique[技术] by (71.8m points)

javascript - Why this operation with date (number of days between 2 dates) return this value?

According to this question, I wrote "my code" (without Math.abs, I don't need it) :

var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date("2011", "09", "28"); // 28 september 2011
var secondDate = new Date("2011", "09", "30"); // 30 september 2011

var notti = ((secondDate.getTime() - firstDate.getTime()) / (oneDay));
if (notti < 1)
    notti = 1;
else
    notti = Math.round(notti);

alert(notti);

and it print 2 (correct).

Now, If I do this :

var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date("2011", "09", "28"); // 28 september 2011
var secondDate = new Date("2011", "10", "01"); // 01 october 2011

var notti = ((secondDate.getTime() - firstDate.getTime()) / (oneDay));
if (notti < 1)
    notti = 1;
else
    notti = Math.round(notti);

alert(notti);

it print 4. Why 4? It should be 3... Do you know about this problem?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The month argument in the date constructor (and other date methods) runs from [0.11] not [1..12] so:

new Date("2011", "09", "28"); // 28 september 2011

is actually Fri Oct 28, not September.


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

...