0

I am using this function to get the mm/dd/yy of tomorrow using javascript:

(dt.getMonth() + 1) + "/" + (dt.getDate() +1 ) + "/" + dt.getFullYear()

Todays date is 9/12/19 and the code above returns 9/13/19. However, I am not sure what this code returns on the day of 9/30/2019. I am not sure how to test this scenario. Does this return 10/1/2019 or does it return 9/31/2019 which is incorrect.

jedu
  • 1,211
  • 2
  • 25
  • 57
  • You can create a specific date and try it yourself to find out: `dt = new Date(2019, 8, 30)` (month numbers in JS start at 0, so use 8, not 9). I would encourage you to update your question to "how can I test this scenario", rather than "what is the result of this scenario". It's the difference between being given a fish to eat, and taught how to catch a fish. –  Sep 13 '19 at 03:13
  • See also: https://stackoverflow.com/questions/563406/add-days-to-javascript-date – JoshG Sep 13 '19 at 03:18
  • @jned29 The +1 for the months is because in JavaScript months are zero-based. – Robby Cornelissen Sep 13 '19 at 03:22
  • Possible duplicate of [JavaScript, get date of the next day](https://stackoverflow.com/questions/23081158/javascript-get-date-of-the-next-day) – jned29 Sep 13 '19 at 03:25

1 Answers1

2

Easiest approach is to just get a date object and add 1 day. It will roll over correctly to the next month:

const date = new Date();
date.setDate(date.getDate() + 1);

console.log(`${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`);

To test the end of month scenario:

const date = new Date(2019, 8, 30); // September 30
date.setDate(date.getDate() + 1);

console.log(`${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`);

The formatting you require corresponds to the format for the English locale, so you could also just use that instead of formatting manually:

console.log(new Date().toLocaleDateString('en', {day: 'numeric', month: 'numeric', year: 'numeric'}));
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156