0

I want to convert this type of Date

22-07-2020 12:00

to

2020-07-07T11:39:02.287Z

how can i do it ?

mohsen Zare
  • 386
  • 1
  • 9
  • 6
    Does this answer your question? [Converting a string to a date in JavaScript](https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript) – jdaz Jul 06 '20 at 07:34

1 Answers1

3

Here's a function to convert a string YYYY-MM-DD hh:mm:ss date time to iso date

function toIsoDate(dateTime){
    const date = dateTime.split(" ")[0].split("-");
    const time = dateTime.split(" ")[1].split(":");
    return new Date(date[2], date[1]-1, date[0], time[0], time[1]);
    // or if you want to return ISO format on string
    return new Date(date[2], date[1]-1, date[0], time[0], time[1]).toISOString();
}

Date accept these parameters: (year, month, day, hours, minutes, seconds, milliseconds), keep in mind that the month value is 0-11, not 1-12, that's why we subtract the month (date[1]) on the function.

const dateTime = "22-07-2020 12:00";
console.log(toIsoDate(dateTime));

2020-07-22T12:00:00.000Z

Owl
  • 6,337
  • 3
  • 16
  • 30