Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you use toLocaleTimeString?

Definition and Usage The toLocaleTimeString() method returns the time portion of a date object as a string, using locale conventions.

How do you get toLocaleString time?

To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions. To display only the time, you can use the toLocaleTimeString() method.


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.


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.


This works for me:

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


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');
}

With locales :

var date = new Date();
date.toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'})