'How do I use .toLocaleTimeString() without displaying AM/PM?
How can I display a digital clock with the format "HH:MM" in Javascript?
The code below displays the digital clock in the format of "HH:MM AM/PM".
main.js
const d = new Date();
const cFormat = d.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
});
Edit: Although the code below works, I'd like to know if there is a way to do this via ".toLocaleTimeString()".
const d = new Date();
const cFormat = d.toLocaleTimeString('en-US', {hour: "2-digit",minute: "2-digit"});
cFormat.replace("AM", "").replace("PM", "");
console.log( 'cFormat -> ', cFormat )
Solution 1:[1]
const d = new Date();
const cFormat = d.toLocaleTimeString('en-US', {hour: "2-digit",minute: "2-digit", hour12: true});
cFormat.replace("AM", "").replace("PM", "");
console.log( 'cFormat -> ', cFormat )
Solution 2:[2]
The replace function doesn't work in place, meaning it doesn't affect the original string. It just returns a new string, so even in the answer you're giving, you still get AM. You can tweak it like this:
const d = new Date();
const cFormat = d.toLocaleTimeString('en-US', {hour: "2-digit",minute: "2-digit"}).replace(/AM|PM/g, "").trim();
console.log(cFormat)
I understand that you want to find a different way other than replacing AM/PM with an empty string, but at this point, it doesn't seem like there's a way to do so other than using military time.
Solution 3:[3]
let time = new Date().toLocaleTimeString().replace("AM", "").replace("PM", "");
console.log(time);
//expected output
//8:03:30
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cristian Mendoza |
| Solution 2 | isaacsan 123 |
| Solution 3 | user17879192 |
