Timezone conversion in a Google spreadsheet

后端 未结 5 1169
长发绾君心
长发绾君心 2021-01-01 10:09

I know this looks simple.

In a Google spreadsheet, I have a column where I enter time in one timezone (GMT) And another column should automatically get time in anoth

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 10:17

    This tutorial was amazingly helpful: https://davidkeen.com/blog/2017/01/time-zone-conversion-in-google-sheets/

    Google Sheets does not have a built in way of converting time zone data but by using the power of Moment.js and Google’s script editor we can add time zone functionality to any sheet.

    These are the files I copied into my script project:

    • https://momentjs.com/downloads/moment-with-locales.js saved as moment.js
    • https://momentjs.com/downloads/moment-timezone-with-data.js saved as moment-timezone.js

    Make sure you add the moment.js script first and have it above the moment-timezone.js script because moment-timezone.js depends on it.

    Then in your other script project, your Code.gs file can look like this:

    var DT_FORMAT = 'YYYY-MM-DD HH:mm:ss';
    
    /**
    https://stackoverflow.com/questions/34946815/timezone-conversion-in-a-google-spreadsheet/40324587
    */
    function toUtc(dateTime, timeZone) {  
      var from = m.moment.tz(dateTime, DT_FORMAT, timeZone);//https://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/
      return from.utc().format(DT_FORMAT);
    }
    
    /**
    https://stackoverflow.com/questions/34946815/timezone-conversion-in-a-google-spreadsheet/40324587
    */
    function fromUtc(dateTime, timeZone) {
      var from = m.moment.utc(dateTime, DT_FORMAT);//https://momentjs.com/timezone/docs/#/using-timezones/parsing-in-zone/
      return from.tz(timeZone).format(DT_FORMAT);
    }
    

提交回复
热议问题