-2

I have a string startDate, and I am trying to convert it to a date obj so I can add a day to it and get a new string "2020-09-16"

My code below is not working though:

  let startDate = "2020-09-15"
  let startDateObj = Date.parse(startDate)
  console.log('startDateObj = ', startDateObj)
  startDateObj.setDate(startDateObj.getDate()+1);
  console.log('startDateObj = ', startDateObj)

produces output:

startDateObj =  1600128000000
(node:517) UnhandledPromiseRejectionWarning: TypeError: startDateObj.getDate is not a function
Martin
  • 1,336
  • 4
  • 32
  • 69
  • Does this answer your question? [Add one day to date in javascript](https://stackoverflow.com/questions/24312296/add-one-day-to-date-in-javascript) – g_bor Sep 18 '20 at 16:34
  • "The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31)." [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) – epascarello Sep 18 '20 at 16:38

1 Answers1

1

Instead off Date.parse(starDate), you'll need to create a new date: = new Date(startDate)

let startDate = "2020-09-15"
let startDateObj = new Date(startDate)
console.log('startDateObj = ', startDateObj)
startDateObj.setDate(startDateObj.getDate()+1);
console.log('startDateObj = ', startDateObj)

Based on comments, formatted to yyyy-mm-dd For more info, please check Format JavaScript date as yyyy-mm-dd

let startDate = "2020-09-15"
let startDateObj = new Date(startDate)

console.log('startDateObj = ', startDateObj.toISOString().split('T')[0]);
startDateObj.setDate(startDateObj.getDate()+1);
console.log('startDateObj = ', startDateObj.toISOString().split('T')[0])

JS Date

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • my output comes out to `2020-09-15T00:00:00.000Z`, if i use startDateObj.toString() it becomes Tue Sep 15 2020 17:00:00 GMT-0700 (Pacific Daylight Time), how can i get the string as `yyyy-mm-dd` ? – Martin Sep 18 '20 at 16:41
  • @Martin Please see my edited answer! Hope it helps! – 0stone0 Sep 18 '20 at 16:45