4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Firebaseでクライアントからサーバー時刻を取得する

Last updated at Posted at 2019-06-20

概要

ウェブアプリだとクライアント側の時刻ズレを考慮して、サーバ側の時刻を取得して使用する事が多いと思います。
Firebaseでこのような方法を実現する場合の方法の紹介になります。

方法

残念ながら調べた限りでは、直接API等で時刻を取得する方法は無いようです。
しかしながら、Firestoreの機能でドキュメント内にサーバ時刻を書き込む機能があるのでそれを利用する事で実現します。
具体的には下記のようになります。

sample.js

// 略 firebase.initializeApp等を実施

export default {
  async getServerTime() {
    // ダミーのコレクションにサーバー時刻を書き込む
    const ref = await firebase
      .firestore()
      .collection('dummy_for_time_get') // 任意のダミーコレクション名
      .doc('time')
    await ref.set({
      timestamp: firebase.firestore.FieldValue.serverTimestamp()
    })
    return new Promise((resolve, reject) => {
      try {
        // 書き込みが終わったらデータを取得して返す
        ref.onSnapshot(snapshot => {
          const timestamp = snapshot.data().timestamp
          resolve(timestamp.toDate())
        })
      } catch (err) {
        reject(err)
      }
    })
  }
}

上記のコードでは下記のような処理を実施します。

  1. Firestoreのダミーコレクションにサーバ時刻(firebase.firestore.FieldValue.serverTimestamp())を書き込む
  2. 書き込んだデータを変更通知で取得

ちょっと手が込みますが、無事取得できました。

参照元

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?