When i try
new Date().toISOString()
I have the following timestamp output
2021-03-25T11:05:10.140Z
I've read somewhere that we can get timezone from the utc or unix timestamp.
But they were not explaining how we can do that.Is this possible ?
When i try
new Date().toISOString()
I have the following timestamp output
2021-03-25T11:05:10.140Z
I've read somewhere that we can get timezone from the utc or unix timestamp.
But they were not explaining how we can do that.Is this possible ?
You can get the host timezone offset for the date using getTimezoneOffset which is minutes to add to the local date and time to UTC (or alternatively, the minutes to subtract from UTC to get local).
Therefore the sign is +ve for west of and -ve for east, which is the opposite of commonly used offsets. The offset in minutes can be converted to +HH:mm using a simple function that reverses the sign and formats the value.
Most offsets since 1900 are even multiples of 15 minutes, prior to that offsets were based on local solar noon so included seconds. So any function that returns an offset as ±HH:mm must include seconds if they are present in the offset.
Since the offset is in minutes, seconds (if present) are represented as decimal minutes. Since 60ths can't be represented exactly by ECMAScript numbers, the minor decimal places need to be dealt with.
E.g. 1 Jan 1800 in Australia/Sydney was +10:04:52 which is represented as -604.8666666666667 minutes. That converts simplistically to +10:04:52.000000000000455, so the decimal seconds need to be rounded to the nearest whole number to get +10:04:52.
/* Get host timezone offset for date
** @param {Date} date : date to get timezone offset for
** @returns {string|undefined} offset as "±HH:mm[:ss]" or
** undefined if date is invalid
** seconds only included if not zero
*/
function getOffset(date = new Date()) {
let z = n => (n < 10? '0' : '') + n;
let m = date.getTimezoneOffset();
let sign = m < 0? '+' : '-';
m = Math.abs(m);
let HH = z(m / 60 | 0);
let mm = z(m % 60 | 0);
let ss = z(Math.round((m % 1) * 60));
return isNaN(m)? void 0 : `${sign}${HH}:${mm}${ss=='00'?'':':'+ss}`;
}
[new Date(1800,0,1), // 1 Jan 1800, offset may have minutes
new Date(2020,0,1), // 1 Jan 2020, may be DST in southern hemisphere
new Date(2020,5,1), // 1 Jun 2020, may be DST in northern hemisphere
new Date(NaN) // invalid date
].forEach(d => console.log(d.toDateString() + ' ' + getOffset(d)));