Search code examples
javascriptdatemoment-timezone

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


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?


Solution

  • 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