create a function that can parse dates from both european and american date standards in javascript

index.tsx
function parseDate(dateString) {
  // check if date is in European or American format
  let dateParts = dateString.split(/(\.|\/|-)/);
  let day, month, year;
  if (dateParts[1] === "." || dateParts[1] === "-") {
    // date is in European format
    day = Number(dateParts[0]);
    month = Number(dateParts[2]);
    year = Number(dateParts[4]);
  } else {
    // date is in American format
    month = Number(dateParts[0]);
    day = Number(dateParts[2]);
    year = Number(dateParts[4]);
  }
  // create date object
  return new Date(year, month - 1, day);
}

// example usage
let europeanDate = "12.04.2022";
let americanDate = "04/12/2022";

console.log(parseDate(europeanDate));  // output: Tue Apr 12 2022 00:00:00 GMT+0300 (Eastern European Summer Time)
console.log(parseDate(americanDate));  // output: Tue Apr 12 2022 00:00:00 GMT+0300 (Eastern European Summer Time)
876 chars
26 lines

This function checks if the date is in European or American format based on the separator used (i.e. "." or "/" or "-"). Once the format is determined, the day, month, and year are extracted and a new Date object is created, taking into account that the month is zero-indexed in the Date constructor.

gistlibby LogSnag