create a function that can parse a date or datetime with different source formats including american standards and iso 8601 in javascript

Here is an example function that can parse a date or datetime with different source formats including American standards and ISO 8601 in Javascript. It makes use of regular expressions to identify and extract different parts of the date or datetime string.

index.tsx
function parseDateTime(dateTimeString) {
  // First, check if the input is already a date object
  if (Object.prototype.toString.call(dateTimeString) === '[object Date]') {
    return dateTimeString;
  }
  
  // Define regular expressions to match different date formats
  const amRegex = /^(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{2}):(\d{2}) (AM|PM)$/;
  const isoRegex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/;
  
  // Try parsing the input using the American date format first
  let match = dateTimeString.match(amRegex);
  if (match) {
    const [, month, day, year, hours, minutes, seconds, amPm] = match;
    const adjustedHours = (hours % 12) + ((amPm === 'PM') ? 12 : 0);
    return new Date(year, month - 1, day, adjustedHours, minutes, seconds);
  }
  
  // If that fails, try parsing using the ISO 8601 format
  match = dateTimeString.match(isoRegex);
  if (match) {
    const [, year, month, day, hours, minutes, seconds, milliseconds] = match;
    return new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds, milliseconds));
  }
  
  // If all else fails, return NaN to indicate an error
  return NaN;
}
1155 chars
29 lines

To use this function, simply pass in a string representing the date or datetime you want to parse, and it will return a Date object if successful or NaN if not. For example:

index.tsx
const date1 = parseDateTime('02/14/2022 10:30:00 AM'); // returns a Date object representing February 14, 2022 at 10:30:00 AM
const date2 = parseDateTime('2022-02-14T10:30:00.000Z'); // also returns a Date object representing the same datetime
const date3 = parseDateTime('not a valid date'); // returns NaN to indicate an error
329 chars
4 lines

gistlibby LogSnag