AndreaNobili
AndreaNobili

Reputation: 43057

How to convert this date in a string having this format using JavaScript?

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?

Upvotes: 0

Views: 48

Answers (1)

Muhammad Fazeel
Muhammad Fazeel

Reputation: 578

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

Upvotes: 1

Related Questions