2

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?

Akash
  • 75
  • 1
  • 8

2 Answers2

3

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

debugger
  • 1,442
  • 1
  • 9
  • 14
  • why in `utcOffset(330)` the argument is taken as 330. I want to make it generic – Akash Sep 19 '22 at 18:44
  • This doesn't provide in hh:mm:ss+|-hh:mm format – Akash Sep 19 '22 at 18:47
  • You can store `moment(date).utcOffset()` in a variable and use it ? – debugger Sep 19 '22 at 18:49
  • `moment.utc(timestamp).utcOffset(moment(timestamp).utcOffset()).format("HH:MM:SSZ")` the command will look something this way for time – Akash Sep 19 '22 at 19:04
  • my conversionDateTime value must be in this format itself. `yyyy-mm-dd hh:mm:ss+|-hh:mm` – Akash Sep 19 '22 at 19:09
  • e.g - `2019-01-01 12:32:45-08:00` – Akash Sep 19 '22 at 19:09
  • How to handle edge case where the time is in "Monrovia - Liberia" -> `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 – Akash Sep 20 '22 at 04:35
  • @Akash You can set the format for that. Try my updated answer. I think this is what you needed. – debugger Sep 20 '22 at 05:33
  • 1
    Thanks - The above updated solution worked for me – Akash Sep 20 '22 at 19:57
1

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.

QT Ray
  • 1,256
  • 8
  • 12