How do I use .toLocaleTimeString() without displaying seconds?

I'm currently attempting to display the user's time without displaying the seconds. Is there a way I can do this using Javascript's .toLocaleTimeString()?

Doing something like this:

var date = new Date();
var string = date.toLocaleTimeString();

will display the user's time with every unit, e.g. currently it displays 3:39:15 PM. Am I able to display that same string, just without the seconds? (e.g. 3:39 PM)


Solution 1:

You can always set the options, based on this page you can set, to get rid of the seconds, something like this

var dateWithouthSecond = new Date();
dateWithouthSecond.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});

Supported by Firefox, Chrome, IE9+ and Opera. Try it on your web browser console.

Solution 2:

I wanted it with date and the time but no seconds so I used this:

var dateWithoutSecond = new Date();
dateWithoutSecond.toLocaleTimeString([], {year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit'});

It produced the following output:

7/29/2020, 2:46 PM

Which was the exact thing I needed. Worked in FireFox.

Solution 3:

This works for me:

var date = new Date();
var string = date.toLocaleTimeString([], {timeStyle: 'short'});

Solution 4:

The value returned by Date.prototype.toLocaleString is implementation dependent, so you get what you get. You can try to parse the string to remove seconds, but it may be different in different browsers so you'd need to make allowance for every browser in use.

Creating your own, unambiguous format isn't difficult using Date methods. For example:

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