Calculating Dates

  • Thread starter Trevor Lawrence
  • Start date
T

Trevor Lawrence

This is a JS question

I am trying to add to a date

This is my code

var firstdate = new Date()
firstdate.setFullYear(2007,10,26)

var number = 1

var newdate = new Date()
newdate.setDate(firstdate.getDate() + number)
alert('firstdate= ' + firstdate + '\nnewdate= ' + newdate)

The alert shows that 1 month and 1 day is added to the date, not 1 day

e.g
firstdate = Mon Nov 26 17:08..... 2007
nwedate = Thurs Dec27 17:08.... 2007

How do I add a specified number of days to the date?
 
I

Ian Haynes

var firstdate = new Date()
firstdate.setFullYear(2007,10,26)

var number = 1

var newdate = new Date()
newdate.setDate(firstdate.getDate() + number)
alert('firstdate= ' + firstdate + '\nnewdate= ' + newdate)

The alert shows that 1 month and 1 day is added to the date, not 1 day

This is because 'var newdate = new Date()' sets newdate to 'now'. This is
the default for a new date.

So you then need to set newdate equal to firstdate.

var newdate = new Date()
newdate.setFullYear(firstdate.getFullYear())
newdate.setDate(firstdate.getDate() + number)
alert('firstdate= ' + firstdate + '\newdate= ' + newdate)

HTH
 
T

Trevor Lawrence

Ian Haynes said:
This is because 'var newdate = new Date()' sets newdate to 'now'. This is
the default for a new date.

So you then need to set newdate equal to firstdate.

var newdate = new Date()
newdate.setFullYear(firstdate.getFullYear())
newdate.setDate(firstdate.getDate() + number)
alert('firstdate= ' + firstdate + '\newdate= ' + newdate)

Ian,
I thought that this would be great, and solve my problem.

But I found a small error. which I managed to solve after a lot of trial and
error and consulting w3schools.com.

So, for anyone who may want to do the same, it should read:
var newdate = new Date()
newdate.setFullYear(firstdate.getFullYear(),firstdate.getMonth(),firstdate.getDate()
+ number)
alert('firstdate= ' + firstdate + '\nnewdate= ' + newdate)

The interesting (and confusing) point is that getFullYear only gets the
year, but setFullYear requires all 3 parameters - year, month, day

Thanks for setting me on the right track
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top