Convert date to another timezone in JavaScript

后端 未结 24 3096
没有蜡笔的小新
没有蜡笔的小新 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:38

    I recently did this in Typescript :

    // fromTimezone example : Europe/Paris, toTimezone example: Europe/London
    private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
      const dateToGetOffset = new Date( 2018, 5, 1, 12 );
    
      const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
      const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );
    
      const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
      const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );
    
      const offset: number = fromTimeHours - toTimeHours;
    
      // convert to msec
      // add local time zone offset
      // get UTC time in msec
      const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
        dateFromTimezone.getUTCMonth(),
        dateFromTimezone.getUTCDate(),
        dateFromTimezone.getUTCHours(),
        dateFromTimezone.getUTCMinutes(),
        dateFromTimezone.getUTCSeconds(),
      );
    
      // create new Date object for different city
      // using supplied offset
      const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );
    
      // return time as a string
      return dateUTC;
    }
    

    I Use "en-UK" format because it is a simple one. Could have been "en-US" or whatever works.

    If first argument is your locale timezone and seconde is your target timezone it returns a Date object with the correct offset.

提交回复
热议问题