290

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)

javadog36
  • 3,025
  • 2
  • 13
  • 7

15 Answers15

505

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.

nrofis
  • 8,975
  • 14
  • 58
  • 113
CJLopez
  • 5,495
  • 2
  • 18
  • 30
  • FYI - This is part of the [ECMAScript Internationalization API](http://www.ecma-international.org/ecma-402/1.0/). It should be available in most modern browsers by now. – Matt Johnson-Pint Jun 19 '14 at 00:21
  • @cept0—the internationalization API supports 24hour format, but it's not widely implemented (Ok in Firefox, Chrome, not in Safari, OmniWeb). – RobG Dec 16 '14 at 11:51
  • I'd rather branch for Safari shenanigans than use anything other than this. Better to trust a browser vendor's resources where issues of locale need to be handled with date/time since they inevitably will need to be handled by any successful product. – Erik Reppen Mar 30 '15 at 02:48
  • 8
    FYI `hour: "2-digit"` not working for me in Chrome 42 nor FF 37 --- `d = new Date(1429524912495).toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit', hour12: true})` returns `"6:15 AM"` in both. – user9645 Apr 23 '15 at 13:57
  • @user9645 report that as a bug to chrome… @CJLopez Why use `navigator.language` rather than just `undefined`? – binki May 19 '15 at 17:34
  • @binki Well, in my case, I have several application that user by multiple customers from several parts of the world Right now, we support chinese, japanese, german, italian, and of course, spanish (my native language) and english (my second language), so using navigator.language will assure me that I'm using the users datetime format. Besides, this can be either set by the computer, or user selected by a combo box – CJLopez May 20 '15 at 14:00
  • @CJLopez but doesn’t just leaving the locale unspecified use the browser’s default locale—no need to deal with `navigator.language` in the first place ;-). – binki May 20 '15 at 18:33
  • @binki - Actually I found out that the combination of `hour: 2-digit` with `hour12: true` causes the `2-digit` to be ignored. Not sure if that is spec operation or not but both Chrome and Firefox do it. – user9645 May 21 '15 at 11:54
  • 24
    use `[]` to leave out a specific locale. That way you stay to the users locale: `toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}` – Hafenkranich Jul 05 '15 at 13:28
  • @user9645 probably not a chrome bug, there is an algorithm to determinate the best format posible, thats why the "empty locale" works: http://www.ecma-international.org/ecma-402/1.0/#BasicFormatMatcher – Raphael Isidro Oct 31 '15 at 02:40
  • 14
    works in chrome 51: `new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', hour12: false}); "17:08"` – rofrol Jun 02 '16 at 15:09
  • in myh chrome didn't need hour12 : false – Carlos Apr 19 '17 at 20:22
  • 1
    yeah, been 4 years since I posted this here, so many thing s have changed. No wonder you no longer need to specify it. Regards – CJLopez Apr 20 '17 at 13:27
  • awsome bro ! var mDate =new Date(date).toLocaleTimeString("en-US", {timeZone: "Asia/Riyadh",hour: '2-digit', minute:'2-digit'}) – Sameer Kazi Jul 31 '17 at 16:03
  • 3
    Here's the documentation of the allowed options (it's based on a separate constructor but the options map one-to-one): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/DateTimeFormat – Brian Peterson Mar 11 '20 at 18:42
  • little late now but when @user9645 said they weren't getting the 2-digit hour, that's because they were including lang/country code `en-US`. The US standard is **no** leading zero on hours, so that was overriding the `hour: '2-digit'` parameter. For example, using a lang/country code like `de-de` with it returns the hours with the leading zero. – ashleedawg Dec 14 '20 at 14:20
  • Use `{hour: 'numeric', minute: '2-digit'}` if you don't want a leading 0 for single-digit hours: 3:39 PM as opposed to 03:39 PM. – devios1 Aug 23 '22 at 15:35
58

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.

drchuck
  • 4,415
  • 3
  • 27
  • 30
41

This works for me:

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

  • 22
    It's worth noting that, as of March 2020, [the timeStyle option is supported only in Chrome and Opera](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/DateTimeFormat), and not in Firefox, Edge/IE, and Safari. If you want broad coverage, it's probably better to stick with the hour and minute options for now. – buckthorn Mar 25 '20 at 15:26
  • For Safari / iOS, this only works in the US where you have AM/PM. en-US will display 3:16 PM, other locales will display 15:16:00. – PassKit May 25 '20 at 05:22
  • 3
    Seems to work in all up-to-date browsers except IE as of Feb 2022. – Orchis Feb 17 '22 at 09:48
12

With locales :

var date = new Date();
date.toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'})
Mickael Austoni
  • 129
  • 1
  • 2
11

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');
}
RobG
  • 142,382
  • 31
  • 172
  • 209
  • 11
    DO NOT parse the string returned from toLocaleTimeString. I had been for a few years without any problem. But then today I noticed it was not working. Turns out there are special unicode characters (e.g. 0x200E, a left-to-right mark) which cannot be processed by Date.parse. Never saw THAT coming. So i'm going to stop using all the locale functions, and just construct my own time-formatted strings. That will save me from evil surprises like this one. – Gabe Halsmer Dec 16 '13 at 17:15
  • @GabeHalsmer—I do not, and never have, recommend allowing Date.parse to parse strings (e.g. the last paragraph [here](http://stackoverflow.com/questions/23629598/check-date-with-current-date-in-jquery/23630535#23630535)). But that is irrelevant here, it's not mentioned at all, you have missunderstood the answer if you think it does (e.g. "**You** can try to parse…"). – RobG Jun 02 '14 at 22:48
  • Nice link. So in summary people must either make their own parse or their own ToString method, because fundamentally Date.prototype.toLocalString and Date.parse are incompatible. Making a ToString seemed like the easiest thing for me to do. But you've implemented you're own parse. So either will work for people. The essential thing I wanted to make everyone aware of was that Date.parse doesn't work with toLocaleString. And it took me hours to trace down this incompatibility because of how subtle it was. The Left-to-Right marks are invisible in Visual Studio's debugger. – Gabe Halsmer Jun 03 '14 at 17:15
  • Cool, another utterly misguided down vote. No wonder people don't want to put their names to them. – RobG Dec 16 '14 at 11:32
  • For storage and transport of dates to other formats, toISOString and getTime probably provide the safest date format for reparsing. I'm not aware of any JS implementation in the last decade not handling the milliseconds version of UTC returned from getTime and ISO values have also been in the specs as a parsable date format for a loooonnng time. But never read back dates from UI elements. That should come from your app layer. And always test in Safari. They've been IE6-level jerks about the date object. – Erik Reppen Mar 30 '15 at 02:45
  • @ErikReppen—all good, but irrelevant here. The question is about displaying local times in a particular format. Parsing the string returned by *toLocaleString* (in the context of this answer) does not mean turning it into a Date, it means trying to identify the seconds part and remove it, which should be obvious from the phrase "*You can try to parse the string to remove seconds*". – RobG Apr 01 '15 at 03:21
10

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.

Josh Withee
  • 9,922
  • 3
  • 44
  • 62
4

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.

ag.
  • 136
  • 6
2

March 2023, it works for me

new Date().toLocaleString('en-GB',{hour12: true, year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute:'2-digit'})
-1

I was able to get only the hour from the users' localeTimeString

const americanTime = date.toLocaleTimeString("en-US", { timeZone: 'America/New_York', hour: 'numeric', hour12: false })
    
const timeInHours = americanTime; 

In this example I used New_York as the user's location.

neil
  • 353
  • 1
  • 8
  • 17
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/late-answers/32142942) – Gabe Jul 05 '22 at 21:11
-1

Can use split Method for using .toLocaleTimeString() without displaying seconds.we can split the seconds and can remove from the string

var date = new Date();
var string = date.toLocaleTimeString();
var arr=string.split(":")
string=arr[0]+":"+arr[1]
console.log(string)
JIBINA
  • 11
  • 3
-3

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/,' ');
karma
  • 903
  • 10
  • 26
-4

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

koanima
  • 567
  • 1
  • 7
  • 19
-5

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;
}
-6

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.

Emu
  • 1
  • 1
-7

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
Mike Lyons
  • 1,748
  • 2
  • 20
  • 33
bradley
  • 445
  • 1
  • 9
  • 17
  • 3
    Please add some explanation to your post. – DigitCart Jan 10 '18 at 18:38
  • 9
    `toLocaleTimeString` returns different string on every browser depending on locale settings. You cannot rely on these positions, you'll get different, probably broken results on other people's browsers. – oriadam Mar 15 '18 at 08:30