简体   繁体   中英

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 )

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 )

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 )

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.

let time = new Date().toLocaleTimeString().replace("AM", "").replace("PM", "");
console.log(time);
//expected output
//8:03:30

A little bit later, but you can do it using spanish format ('es-ES') and setting hour and minute as '2-digit'.

const dat = new Date();
dat.toLocaleString('es-ES', {hour: '2-digit', minute: '2-digit'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM