Home > Enterprise >  How to get timezone offset as ±hh:mm in javascript?
How to get timezone offset as ±hh:mm in javascript?

Time:09-20

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?

CodePudding user response:

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`);
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.

CodePudding user response:

Are you trying to achieve this? 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.utc(date).utcOffset(utc).format('h:mm A ZZ'))
let utc2 = date.getTimezoneOffset();
console.log(moment.utc(date).utcOffset(utc2).format('h:mm A ZZ'))
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Update : Is this according to your expected output?

const date = new Date();
let utc = moment(date).utcOffset()
console.log(moment(date).utcOffset(utc).format())
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Reference : Display

  • Related