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

Time:09-30

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:

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(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

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.

  • Related