0

I am working on a JavaScript application and I am finding some difficulties trying to format a date.

So I have a situation like this. I am creating an object like this:

returnedEvent = {
  title: eventEl.innerText,
  startTime: returnedEvent.startTime,
  duration: returnedEvent.duration
}

As you can see in the previous snippet I have the field:

startTime: returnedEvent.startTime,

that contains a date object in this format:

Mon Feb 20 2017 07:00:00 GMT-0800 (Ora standard del Pacifico USA)

Ok but I need to convert this data in a string like this:

2017-02-20T07:00:00

What could be a smart way to achieve this task and convert the data in the desired string?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 1
    Try `.toISOString().substr(0, 19);` –  May 28 '20 at 11:39
  • 1
    ↑ That would shift the time to UTC, so it will be eight hours off in this case. Refer to https://stackoverflow.com/questions/17415579/ if you need to preserve local time. – myf May 28 '20 at 11:44

1 Answers1

1
let date = new Date('Mon Feb 20 2017 07:00:00 GMT-0800 (Ora standard del Pacifico USA)')
console.log(date.toISOString().replace(/\.\d+/, ""))
// Result  2017-02-20T15:00:00Z
let date1 =  new Date('Mon Feb 20 2017 07:00:00 GMT-0800 (Ora standard del Pacifico USA)').toISOString().substr(0, 19)
console.log(date1)
// result 2017-02-20T15:00:00
Muhammad Fazeel
  • 548
  • 6
  • 17