admin管理员组文章数量:1403200
I can get the Timezone offset with the following mand 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 mand as:
new Date().getTimezoneOffset()
-> -330 and using moment
moment().utcOffset()
as 330.
However, how do I get the format as ±hh:mm?
Share Improve this question asked Sep 19, 2022 at 17:50 AkashAkash 1331 gold badge1 silver badge12 bronze badges 4-
the final time should be something like
hh:mm:ss+|-hh:mm
– Akash Commented Sep 19, 2022 at 18:46 - What did you mean by that?can you show an expected format with times? – debugger Commented Sep 19, 2022 at 18:58
- yyyy-mm-dd hh:mm:ss+|-hh:mm. This is the full picture – Akash Commented Sep 19, 2022 at 19:08
-
date and time format. e.g -
2019-01-01 12:32:45-08:00
– Akash Commented Sep 19, 2022 at 19:08
3 Answers
Reset to default 5If 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./downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Reference : Display
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.
本文标签: dateHow to get timezone offset as 177hhmm in javascriptStack Overflow
版权声明:本文标题:date - How to get timezone offset as ±hh:mm in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744380051a2603457.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论