开发者

Javascript Add Date Problem

I've this snippet:

var d1 = parseInt( document.get开发者_C百科ElementById('day1').value );
var m1 = parseInt( document.getElementById('month1').value );
var y1 = parseInt( document.getElementById('year1').value );

var dt = new Date();
dt.setYear(y1);
dt.setMonth(m1);
dt.setDate(d1 + 1);

document.getElementById('day2').value = dt.getDate();
document.getElementById('month2').value = dt.getMonth();
document.getElementById('year2').value = dt.getYear();

My goal is, to automatically init value of date2 by adding 1 day from date1. However, when I fill :

 day1 = 32
 month1 = 1
 year1 = 2009

I got :

 day1 = 5
 month1 = 2
 year1 = 2009

I don't know what is going on. Do you guys know the solutions?


The JavaScript Date object handles months as zero-based numbers (0-Jan,1-Feb,...,11-Dec).

Also you can have problems with the set methods, I would recommend you to use the Date constructor:

var d1 = +document.getElementById('day1').value;
var m1 = +document.getElementById('month1').value - 1; // zero based!!
var y1 = +document.getElementById('year1').value;

var dt = new Date(y1, m1, d1);


See The Add Days To A JavaScript Date example.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜