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

JavascriptTime

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

This works for me:

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

Solution 4 - Javascript

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

Solution 5 - Javascript

With locales :

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

Solution 6 - Javascript

I've also been looking for solution to this problem, here's what I eventually came up with:

function getTimeStr() {
    var dt = new Date();
    var d = dt.toLocaleDateString();
    var t = dt.toLocaleTimeString();
    t = t.replace(/\u200E/g, '');
    t = t.replace(/^([^\d]*\d{1,2}:\d{1,2}):\d{1,2}([^\d]*)$/, '$1$2');
    var result = d + ' ' + t;
    return result;
}

You can try it here: http://jsfiddle.net/B5Zrx/

\u200E is some formatting character that I've seen on some IE version (it's unicode left-to-right mark).

I assume that if the formatted time contains something like "XX:XX:XX" then it must be time with seconds and I remove the last part, if I don't find this pattern, nothing is changed. Pretty safe, but there is a risk of leaving seconds in some weird circumstances.

I just hope that there is no locale that would change the order of formatted time parts (e.g. make it ss:mm:hh). This left-to-right mark is making me a bit nervous about that though, that is why I don't remove the right-to-left mark (\u202E) - I prefer to not find a match in this case and leave the time formatted with seconds in such case.

Solution 7 - Javascript

With date and no leading 0 for hour:

let d = new Date(2022, 2, 21, 7, 45, 0);
let s = d.toLocaleString([], { dateStyle: 'short', timeStyle: 'short' });
console.log(s);
// '2/21/22, 7:45 AM'

This is supported by all modern browsers.

Solution 8 - Javascript

You can try this, which is working for my needs.

var d = new Date();
d.toLocaleTimeString().replace(/:\d{2}\s/,' ');

or

d.toLocaleString().replace(/:\d{2}\s/,' ');

Solution 9 - Javascript

Here's a function that will do it, with comments that explain:

  function displayNiceTime(date){
    // getHours returns the hours in local time zone from 0 to 23
    var hours = date.getHours()
    // getMinutes returns the minutes in local time zone from 0 to 59
    var minutes =  date.getMinutes()
    var meridiem = " AM"

    // convert to 12-hour time format
    if (hours > 12) {
      hours = hours - 12
      meridiem = ' PM'
    }
    else if (hours === 0){
      hours = 12
    }

    // minutes should always be two digits long
    if (minutes < 10) {
      minutes = "0" + minutes.toString()
    }
    return hours + ':' + minutes + meridiem
  }

Since, as others have noted, toLocaleTimeString() can be implemented differently in different browsers, this way gives better control.

To learn more about the Javascript Date object, this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Solution 10 - Javascript

I think the original question can easily be answered with something being overlooked so far: a simple string split. The time being returned is a text string, just split it on the ":" delimiter and reassemble the string the way you want. No plug ins, no complicated scripting. and here ya go:

var myVar=setInterval(function(){myTimer()},1000);

function myTimer() {
    var d = new Date();
    currentNow = d.toLocaleTimeString();
    nowArray = currentNow.split(':');
    filteredNow = nowArray[0]+':'+nowArray[1];
    document.getElementById("demo").innerHTML = filteredNow;
}

Solution 11 - Javascript

Even though this is an older question, I had the same one myself recently, and came up with a more simple solution using regular expressions and the string replace function as another alternative (no need for external js libraries or reliance on the ECMAScript Internalization API):

var d = new Date();
var localeTime = d.toLocaleTimeString();
var localeTimeSansSeconds = localeTime.replace(/:(\d{2}) (?=[AP]M)/, " ");

This approach uses a regex look-ahead to grab the :ss AM/PM end of the string and replaces the :ss part with a space, returning the rest of the string untouched. (Literally says "Find a colon with two digits and a space that is followed by either AM or PM and replace the colon, two digits, and space portion with just a space).

This expression/approach only works for en-US and en-US-like Locales. If you also wanted a similar outcome with, say, British English (en-GB), which doesn't use AM/PM, a different regular expression is needed.

Based on the original questioner's sample output, I assume that they were primarily dealing with American audiences and the en-US time schema.

Solution 12 - Javascript

Simply convert the date to a string, and then concatenate the substrings you want out of it.

let time = date.toLocaleTimeString();
console.log(time.substr(0, 4) + time.substr(7, 3))
//=> 5:45 PM

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjavadog36View Question on Stackoverflow
Solution 1 - JavascriptCJLopezView Answer on Stackoverflow
Solution 2 - JavascriptdrchuckView Answer on Stackoverflow
Solution 3 - JavascriptFloris LooijesteijnView Answer on Stackoverflow
Solution 4 - JavascriptRobGView Answer on Stackoverflow
Solution 5 - JavascriptMickael AustoniView Answer on Stackoverflow
Solution 6 - Javascriptag.View Answer on Stackoverflow
Solution 7 - JavascriptJosh WitheeView Answer on Stackoverflow
Solution 8 - JavascriptkarmaView Answer on Stackoverflow
Solution 9 - JavascriptkoanimaView Answer on Stackoverflow
Solution 10 - JavascriptFrank EastesView Answer on Stackoverflow
Solution 11 - JavascriptEmuView Answer on Stackoverflow
Solution 12 - JavascriptbradleyView Answer on Stackoverflow