'How to get hour and minute as numeric values (not string) in local timezone from Javascript Date object?
I have a Date in UTC format, and want to get the hour and minute but in the local time zone the browser is running in - and without me specifying the timezone explicitly, just using the default used by the browser. I know I can get the whole date time in the local zone as a string using Date.toLocaleTimeString() or Date.toString() but don't want to have to parse out the hour and minute.
Also I can get the numeric hour and minute from a Date using Date.getHours() and getMinutes(), but this won't be in the local time zone - or will it? (ironically my local timezone is UTC so not sure how to test)
Thanks
EDIT: Answering my own question, see below
Solution 1:[1]
So a Javascript Date object is apparently not in a timezone as such, it's basically just the number of milliseconds since the Unix Epoch as per Date.now() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
So what I didn't realise until I checked the docs ;-) was that Date.getHours() returns the numeric hours value according to local time (i.e. time in the timezone of the device running the code) and not UTC time (which I was trying to avoid). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
So Date.hours() gives me exactly what I want (if for some reason I did want UTC, I could use Date.getUTCHours() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours
Then I can just use Date.getMinutes() to get the minute value of the Date and that's not affected by timezone anyway so all good :)
Solution 2:[2]
You can use Date.prototype.getHours
and Date.prototype.getMinutes
to get the hours and minetes from a string date like: 2022-01-08 14:00:00.
Use this code:
var d = new Date(/* A example date: '2022-01-08 14:00:00'*/);
var h = d.getHours();
var m = d.getMinutes();
// Whit the example date you get in the console: 'Time: 14:00.'
console.log('Time: '+ h + ' : ' + m + '.');
Solution 3:[3]
I would use toLocalstring
and then i would convert string to number.
function getNumericHourAndMinute() {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
const d = new Date().toLocaleString('en-US', { timeZone: tz, timeStyle: 'short', hour12: false });
const p = d.split(':');
return [Number(p[0]), Number(p[1])];
}
console.log(getNumericHourAndMinute());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alex Kerr |
Solution 2 | |
Solution 3 |