Sometimes, we want to format a JavaScript date object into a time string but omit the seconds from the string.
In this article, we’ll look at ways to use the toLocaleTimeString
method to return a formatted time string without including the seconds in the string.
Set hour and minute to 2-digit
We can set the hour
and minute
properties to '2-digit'
to get rid of the seconds from the returned time string.
For instance, we can write:
const dateWithoutSecond = new Date();
const formatted = dateWithoutSecond.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
});
console.log(formatted)
We create a Date
instance and store it in the dateWithoutSecond
variable.
Then we call toLocateString
on it with an object with the hour
and minute
options set to '2-digit'
to return a time string without the seconds.
So formatted
would be a string like '04:05 PM’
.
Set timeStyle to short
We can also set the timeStyle
option to short to omit the seconds from the returned time string.
For instance, we can write:
const dateWithoutSecond = new Date();
const formatted = dateWithoutSecond.toLocaleTimeString([], {
timeStyle: 'short'
});
console.log(formatted)
to do this.
Then formatted
is something like '4:07 PM’
.
Conclusion
We can set various options with toLocateTimeString
to return a time string without the seconds part.