How to format a date as minutes in Javascript
Say we have a Date
object representing five minutes:
const fiveMinutes = new Date(0, 0, 0, 0, 5, 0);
How can you format this date to display "5:00"?
The easiest way is using Intl.DateTimeFormat
browser API (see docs). This formats the Date as a string, according to a given locale. By passing in the options to only include the minutes
and seconds
, we can obtain our date:
const formattedDate = Intl.DateTimeFormat("en-US", {
minute: "numeric",
second: "numeric",
}).format(fiveMinutes);
Alternative 1: Date.toLocaleTimeString
Another good option to format the date as time is using Date.toLocaleTimeString
(docs). This is equivalent with the option above.
// show full time part
fiveMinutes.toLocaleTimeString();
// show just minutes and seconds
fiveMinutes.toLocaleTimeString(undefined, { minute: "numeric", second: "numeric"})
Alternative 2: Concatenating time parts
Another approach is to extract the parts of the time using Date.getMinutes
and Date.getSeconds
methods and then concatenating them:
const minutes = fiveMinutes.getMinutes();
const seconds = fiveMinutes.getSeconds();
const paddedSeconds = seconds.toString().padStart(2, "0");
const formattedDate = `${minutes}:${paddedSeconds}`;
The downside of this approach is that it does not take the user locale into account and is error prone - since we are manually stiching things together.
For a broader discussion of formatting options, take a look at https://www.freecodecamp.org/news/how-to-format-dates-in-javascript.
How do you format dates as time? Share your thoughts in the comments below!
Member discussion