Home > Net >  How to parse dates in javascript?
How to parse dates in javascript?

Time:12-16

How can I parse dates coming in this example format 7 July 2021 at 1:36:23 AM Z in pure javascript? Tried a lot of things even with moment.js but was not fruitful. I presume the at in the middle of the date is the problem. Any help would be appreciated. Thanks in advance

Edit :

Tried the replace() function as mentioned in the comments, It worked perfectly for chrome, but safari is throwing Invalid Date error.

Sample code:

function convertUTCDateToLocalDate(date) {
    let newDate = new Date(date);
    let options = {
        year: "numeric",
        month: "long",
        day: "2-digit",
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    };
    return newDate.toLocaleDateString("en", options);
}
let dateString = "7 July 2021 at 1:36:23 AM Z"
console.log(convertUTCDateToLocalDate(dateString.replace('at', ''));

CodePudding user response:

You can use replace regex dateString.replace(/at|Z/g, '') for Safari, it worked for Safari and Chrome

CodePudding user response:

The best option would be to request an ISO 8601 formatted date-time from wherever your string is coming from. Maybe there is an API option that allows you to pass the format. If you are using some custom input there might be an option to retrieve an ISO 8601 formatted string as well.


If for some reason you cannot change the string at its source you could always manually converted in into the correct format.

const months = {
  january: 1,
  february: 2,
  march: 3,
  april: 4,
  may: 5,
  juny: 6,
  july: 7,
  august: 8,
  september: 9,
  october: 10,
  november: 11,
  december: 12,
};
const meridiems = {
  am: 0,
  pm: 12,
};

const input = "7 July 2021 at 1:36:23 AM Z";
let [day, month, year, _at, time, meridiem, offset] = input.split(" ");
let [hour, minute, second] = time.split(":");

day = day.padStart(2, "0");

month = months[month.toLowerCase()];
month = month.toString().padStart(2, "0");

hour = parseInt(hour, 10) % 12   meridiems[meridiem.toLowerCase()];
hour = hour.toString().padStart(2, "0");

const iso8601 = `${year}-${month}-${day}T${hour}:${minute}:${second}${offset}`;

console.log(iso8601);
console.log(new Date(iso8601));

  • Related