Formatting Javascript datetime month year

Viewed 90

I'm trying to format Javascript datetime, year and month information to something like this:

//"Mon, Nov 5 08:46:20 PM"

To do that, I am following Mozilla documentation here as shown below:

var options = {
  weekday: 'short',
  month: 'short',
  day: 'numeric',
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hour12: true
};
console.log(new Date().toLocaleDateString('en-US', options));
// always returns "Mon, Nov 5, 8:44:10 PM"

Why is the hour in 1-digit format although I specified it as '2-digit'? How can I achieve the format stated in the beginning of this question? Thank you in advance for your answers!

1 Answers

You can use a RegExp and String.prototype.replace() to fix that issue:

const options = {
  weekday: 'short',
  month: 'short',
  day: 'numeric',
  hour: "2-digit",
  minute: "2-digit",
  second: "2-digit",
  hour12: true
};

// Tue, Nov 6, 04:04:55 AM: 
console.log(new Date(1541473495383).toLocaleDateString('en-US', options).replace(/, (\d):/, ', 0$1:'));

// Tue, Nov 6, 10:04:55 AM:
console.log(new Date(1541495095383).toLocaleDateString('en-US', options).replace(/, (\d):/, ', 0$1:'));

// Now:
console.log(new Date().toLocaleDateString('en-US', options).replace(/, (\d):/, ', 0$1:'));

What .replace(/, (\d):/, ', 0$1:') does is:

  • Match the hour part (that comes after a comma and a space and before a colon) only when it has a single digit (\d); otherwise, it won't match and it won't replace anything.

  • Captures that digit.

  • Replace the whole match with exactly the same thing but adding an additional 0 before the hour digit, which we can access in the replacement string as $1.

Related