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
Add a ment  | 

3 Answers 3

Reset to default 5

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./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