0

I've this snippet:

var d1 = parseInt( document.getElementById('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?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

can you tell me more, what problem would that be?
1

See The Add Days To A JavaScript Date example.

1 Comment

Sadly this does not work. It does not account correctly for days which are longer or shorter than 24 hours (the leap year days). For example, on the script at this site, try this date: 7/11/2010 (November, 7 2010) while in the eastern time zone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.