1

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 )
Mister Jojo
  • 16,804
  • 3
  • 16
  • 39
  • Does this answer your question? [Javascript .toLocaleString() not honoring '2-digit'](https://stackoverflow.com/questions/60230961/javascript-tolocalestring-not-honoring-2-digit) – Mister Jojo Sep 11 '21 at 22:20
  • your code doesn't display in in the format of "HH:MM AM/PM". in my country. – Mister Jojo Sep 11 '21 at 22:26
  • Are you trying to display military time, or do you want to display AM/PM time just without the AM/PM? – isaacsan 123 Sep 11 '21 at 22:26
  • @isaacsan123 I'm just trying to display it with the 12-hour format that excludes the AM/PM. I posted my answer, although I'm still looking for a better solution. –  Sep 11 '21 at 22:29

4 Answers4

1

this way

const HH_MM = {hour: '2-digit', minute: '2-digit' }

let cFormat = new Date()
               .toLocaleTimeString('en-US', HH_MM)
               .replace(/AM|PM/,'') 

console.log( 'cFormat -> ', cFormat )
Mister Jojo
  • 16,804
  • 3
  • 16
  • 39
0
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 )
0

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.

isaacsan 123
  • 825
  • 6
  • 9
0
let time = new Date().toLocaleTimeString().replace("AM", "").replace("PM", "");
console.log(time);
//expected output
//8:03:30