javascriptdateutcdatetimeoffset

How to convert date string which contains time offset to another format?


I'm receiving this kind of string as date "2020-09-09T12:41:41 -04:00". It seems like this string contains time offset. I need to convert this to "3/15/2020, 1:23:09 PM " format. How can I achieve this?

I tried to create new Date object with that string but it shows me Invalid Date.


Solution

  • You can use INTL DateTime format after you remove the illegal space

    const d = new Date("2020-09-09T12:41:41-04:00")
    console.log(d)
    
    const options = {
      year: "numeric",
      month: "numeric",
      day: "numeric",
      hour : "numeric",
      minute : "numeric",
      second : "numeric",
    };
    const dateString = new Intl.DateTimeFormat("en-US", options).format(d);
    console.log(dateString);

    Alternatively have full control

    const toAMPM = hhmmss => {
      const [hours, minutes, seconds] = hhmmss.split(":");
      const formatHours = hours % 12 || 12;
      const ampm = hours < 12 ? "AM" : "PM";
      return `${+formatHours}:${minutes}:${seconds} ${ampm}`;
    };
    const convertTime = dateString => {
      const d = new Date(dateString).toISOString();
      const [_, yyyy, mm, dd, time] = d.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}:\d{2}:\d{2})\./);
      return `${+mm}/${+dd}/${yyyy}, ${toAMPM(time)}`;
    };
    
    console.log(convertTime("2023-02-28T12:41:41-04:00"));