LoginSignup
7
3

More than 5 years have passed since last update.

バックエンドでUTCで管理してフロントでは現地時間で表示する方法

Last updated at Posted at 2017-08-16

世界各国から利用されるサービスを作る際にUTC→現在位置のタイムゾーン変換ができると一気にグローバルなサービスになるよね?? じゃあやっちゃいましょうー

前準備

Google デベロッパー登録をする

デベロッパーサイトでAPIの認可

  • Google Maps JavaScript API
  • Google Maps Geolocation API
  • Google Maps Time Zone API

を有効にする

実際にやってみる

GOOGLE_API_KEYのセット

process.env.GOOGLE_API_KEY = 'AIz*****************';

Google Maps Geolocation APIを利用して現在位置の緯度経度取得

function getGeolocation() {
    if (!'geolocation' in navigator) return { latitude: undefined, longitude: undefined };

    return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(
        (position) => resolve({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        }),
        (err) => reject(`ERROR(${err.code}): ${err.message}`)
      );
    });
  }

Google Maps Time Zone APIを利用してタイムゾーンを取得する

緯度経度を入れてtimestampをセットして叩くとその箇所のタイムゾーンが手に入る

UTC → UnixTimestamp
function utcToUnixTime(ts) {
  return Date.parse( ts.replace( /-/g, '/') ) / 1000;
}

utcToUnixTime("2017-10-14T00:00:00Z");
API押下

(JSのコードはまだ作っていないのでかけたら今後書きますー)
https://maps.googleapis.com/maps/api/timezone/json?location=48.5643009,136.627638&timestamp=1458000000&key=AIz*****************

{
   "dstOffset" : 0,
   "rawOffset" : 36000,
   "status" : "OK",
   "timeZoneId" : "Asia/Vladivostok",
   "timeZoneName" : "Vladivostok Standard Time"
}

mement.jsで変換!!

moment(2017-08-10T12:34:56.008Z).tz(Asia/Vladivostok).format()

参考

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3