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