Categories
Uncategorised

How `parse` works – date-fns ?

const dateStr = '2023-02-22'
const dateFormat = 'yyyy-MM-dd'
const newDate = format(new Date(dateStr))
const parsedDate = format(parse(dateStr, dateFormat, new Date()))

It’s quite an exciting thing that I found recently. parse function in date-fns is doing a kind of “character for-loop” to match the date format that you provided and then adjusting the timezone offset for you. This is why it’s the main reason why the date newDate and parsedDate are getting created differently.

function parse(dateString, formatString, referenceDate) {
  const formatParts = formatString.split(/[\s-/:]+/);
  const dateParts = dateString.split(/[\s-/:]+/);

  let year, month, day, hour, minute, second;

  for (let i = 0; i < formatParts.length; i++) {
    const formatPart = formatParts[i];
    const datePart = dateParts[i];

    if (formatPart === 'yyyy') {
      year = parseInt(datePart, 10);
    } else if (formatPart === 'MM') {
      month = parseInt(datePart, 10) - 1;
    } else if (formatPart === 'dd') {
      day = parseInt(datePart, 10);
    } else if (formatPart === 'HH') {
      hour = parseInt(datePart, 10);
    } else if (formatPart === 'mm') {
      minute = parseInt(datePart, 10);
    } else if (formatPart === 'ss') {
      second = parseInt(datePart, 10);
    }
  }

  console.log(year, month, day, hour, minute, second);
  const date = new Date(year, month, day, hour, minute, second);

  if (referenceDate) {
    const timeZoneOffset = referenceDate.getTimezoneOffset();
    const referenceTimestamp = referenceDate.getTime();

    return new Date(referenceTimestamp + timeZoneOffset * 60 * 1000);
  }

  return date;
}