I can get the Timezone offset with the following command as:
new Date().getTimezoneOffset()
-> -330 and using moment
moment().utcOffset()
as 330.
However, how do I get the format as ±hh:mm?
I can get the Timezone offset with the following command as:
new Date().getTimezoneOffset()
-> -330 and using moment
moment().utcOffset()
as 330.
However, how do I get the format as ±hh:mm?
If you prefer moment.js
you can use .format
for formatting date or time.
const date = new Date();
let utc = moment(date).utcOffset()
console.log(moment(date).utcOffset(utc).format("YYYY-MM-DD HH:mm:ss Z"))
//and for `+00:00` it will be :
console.log('for GMT +0000 : '+ moment(date).tz('Africa/Monrovia').format('YYYY-MM-DD HH:mm:ss Z'))
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Reference : Display
utcOffset(330)
the argument is taken as 330. I want to make it generic –
Feeder moment(date).utcOffset()
in a variable and use it ? –
Yb moment.utc(timestamp).utcOffset(moment(timestamp).utcOffset()).format("HH:MM:SSZ")
the command will look something this way for time –
Feeder yyyy-mm-dd hh:mm:ss+|-hh:mm
–
Feeder 2019-01-01 12:32:45-08:00
–
Feeder Tue Sep 20 2022 03:20:04 GMT+0000
and with the above command it returns 2022-09-20 03:20:04Z
which is not in the correct format. expected is 2022-01-01 10:42:45+00:00
(can give + or - does not matter) this is google's conversion format –
Feeder The answer of QT Ray is a good point to start and helped me to solve the issue but actually has quite a few issues like trying to overwrite a numeric variable with a string or adding the minus in front of the string when the offset is positive.
Here is my working solution:
getTimezoneOffset(offset) {
const offsetHours = Math.floor(Math.abs(offset / 60));
const offsetMins = Math.abs(offset % 60);
return (offset < 0 ? '-' : '+') + (offsetHours < 10 ? '0' : '') + offsetHours + ':' + (offsetMins < 10 ? '0' : '') + offsetMins;
}
You won't be able to do it without a third-party library or manually converting the value with functionality.
You can do something like:
const offset = new Date().getTimezoneOffset();
let offsetHours = parseInt(Math.abs(offset/60));
let offsetMins = Math.abs(offset%60);
let formattedOffset;
if (offsetHours < 10) offSetHours = '0' + offsetHours;
if (offsetMins < 10) offsetMins = '0' + offsetMins;
if (offset < 0) {
formattedOffset = '+' + offsetHours + ':' + offsetMins;
} else if (offset > 0) {
formattedOffset = '-' + offsetHours + ':' + offsetMins;
} else if (offset === 0) {
formattedOffset = 'Z';
}
That should get you pretty close.
© 2022 - 2024 — McMap. All rights reserved.
hh:mm:ss+|-hh:mm
– Feeder2019-01-01 12:32:45-08:00
– Feeder