Convert date to another timezone in JavaScript

后端 未结 24 3093
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 04:45

I am looking for a function to convert date in one timezone to another.

It need two parameters,

  • date (in format \"2012/04/10 10:10:30 +0000\")
24条回答
  •  别跟我提以往
    2020-11-21 05:20

    If you don't want to import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.

    // Specifying timeZone is what causes the conversion, the rest is just formatting
    const options = {
      year: '2-digit', month: '2-digit', day: '2-digit',
      hour: '2-digit', minute: '2-digit', second: '2-digit',
      timeZone: 'Asia/Jakarta',
      timeZoneName: 'short'
    }
    const formatter = new Intl.DateTimeFormat('sv-SE', options)
    const startingDate = new Date("2012/04/10 10:10:30 +0000")
    
    const dateInNewTimezone = formatter.format(startingDate) 
    console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7

    Offsets, daylight saving, and changes in the past will be taken care of for you.

提交回复
热议问题