February 2026

Formatting Dates in JavaScript with Intl.DateTimeFormat

Logging When

I'm working on logging for the next version of bitty. I want to include a timestamp as part of the output. That sent me down the rabbit hole of JavaScript dates and times. Here's where I ended up:

JavaScript

function timestamp(datetime) {
  const parts = {}
  new Intl.DateTimeFormat(undefined,
    {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      fractionalSecondDigits: 3,
      hour12: false,
    })
    .formatToParts(datetime)
    .filter((part) => part.type !== "literal")
    .forEach((part) => parts[part.type] = part.value);
  const date = [parts.year, parts.month, parts.day].join("-");
  const time = [parts.hour, parts.minute, parts.second].join(":");
  return `${date}T${time}.${parts.fractionalSecond}`;
}


const currentTime = new Date();
const outputEl = document.querySelector("#datetime");
outputEl.innerHTML = timestamp(currentTime);

Here's what it looks like:




Everything I need. Nothing I don't.

-a

end of line

Endnotes

The example has millisecond output. I remove that depending on the context. If you don't need it, you can remove fractionalSecondDigits: 3 from the options and .${parts.fractionalSecond} from the return value.

  • The first argument passed to Intl.DateTimeFormat determines the locale/timezone.
  • Passing undefined as the first argument to Intl.DateTimeFormat sets it up to use the current locale of the process running the script.
  • This is only meant for display in the active console. I skip identifying the timezone. It's just wherever you're running the process.
  • Because there's no timezone info this isn't a valid ISO 8610, RFC 3339, or RFC 9557 datetime. I'm cool with that. It's for folks to look at, not for coordinating systems.
  • I store the datetime data as Date objects in the raw logs. It's available as UTC if needed.

References