4

I want to show time in 12 hours format without using the AM and PM. For example 3:45 only and not 3:45 PM or 3:45 AM. How I can modify the toLocaleTimeString() to not show the PM AM but in 12 number format?

var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
console.log(newTime);
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128
  • Why don't you extract the required substring out of `newTime`? – 31piy Apr 02 '19 at 15:40
  • I was hoping to use any built in function from `toLocalTimeString()` – Mona Coder Apr 02 '19 at 15:41
  • It doesn't make sense, and that's why there doesn't seem any ready-made option available to do this. – 31piy Apr 02 '19 at 15:43
  • There's no preset to do that you'll just have to grab a substring that doesn't contain AM/PM – Alex W Apr 02 '19 at 15:44
  • Follow this link: [enter link description here](https://stackoverflow.com/questions/10211145/getting-current-date-and-time-in-javascript) it will show you all you need. – OsamaD Apr 02 '19 at 15:45

3 Answers3

7

.toLocaleTimeString() did not have any override to do so.

There are multiple ways to do so.

Replace AM/PM by blank:

    var minsToAdd = 45;
    var time = "15:00";
    var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
    console.log(newTime.replace("AM","").replace("PM",""));

Using custom JavaScript function:

   function formatTime(d) {
      function z(n){return (n<10?'0':'')+n}
      var h = d.getHours();
      return (h%12 || 12) + ':' + z(d.getMinutes());
    }

    var minsToAdd = 45;
    var time = "15:00";
    var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000);
    console.log(formatTime(newTime));
halfer
  • 19,824
  • 17
  • 99
  • 186
D Mishra
  • 1,518
  • 1
  • 13
  • 17
2

it's very ez.

    const date24 = new Date();
    const data24Time = date24.toLocaleTimeString('en-IT', { hour12: false })
    console.log("24 h : ",data24Time)
    // 24 h :  20:26:09
    
    
    const date12 = new Date();
    const data12Time = date12.toLocaleTimeString('en-IT')
    console.log("12 h : ",data12Time)
    // 12 h :  8:26:09 PM
    
    
    
    
    // toLocaleTimeString('{languege for show time}-{languege for set}')
Mm.Mirzaei.dev
  • 333
  • 3
  • 10
1

formats below assume the local time zone of the locale; America/Los_Angeles for the US

US English uses 12-hour time with AM/PM console.log(date.toLocaleTimeString('en-US')); "7:00:00 PM"

For more information, visit official docs here

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81