1

I'm trying to increment one day to a given date. My code, inspired by this answer, looks like:

var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(date.getDate() + 1);

However, I'm seeing a strange behaviour. Today is December 5th, 2019. If the user selects January 1, 2020 (stored in date variable), then backupDate ends up being January 2nd, 2019, instead of 2020. What is wrong with this code? How should I go about incrementing the date, if what I'm doing is wrong?

Note: because of whatever policies my company has, I can't use any JavaScript library other than jQuery.

victor.ja
  • 811
  • 1
  • 7
  • 27
Fernando Gómez
  • 464
  • 1
  • 5
  • 19

3 Answers3

1

new Date() returns the current Date(example: 05/12/2019). You are just changing the date alone in current date. Still the year is 2019.

it should be like,

date.setDate(date.getDate() + 1);

if you can't change the original date object, then it can be done like this,

var changedDate = new Date(date);
changedDate.setDate(changedDate.getDate() + 1);
Unknown
  • 531
  • 5
  • 18
0
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(new Date(date).getDate() + 1);
  • the date variable holds a date like 2019/01/02 as per the problem. backupDate is just holding a date object. we will add 1 day to date object of 'date' variable like new Date(date).getDate() + 1 and pass it to setDate Method of Date prototype. – Pranav Ramachandran Dec 05 '19 at 21:32
0

nextDay is one day after date:

var date = getDateFromUIControl();
var nextDay = new Date(date.getYear(), date.getMonth(), date.getDate()+1);

Also you don't need to worry about overflowing d.getDate()+1 (e.g. 31+1) - the Date constructor is smart enough to go into the next month.

Matt
  • 20,108
  • 1
  • 57
  • 70