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?
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>
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.