LoginSignup
0
0

More than 3 years have passed since last update.

【Vue × Firebase】serverTimestamp()をjavascriptのデータ型で取得

Last updated at Posted at 2021-04-23

ServerTimestampとは

時間軸を全てサーバーに預けてしまうことによってモバイルの個体差によるずれを解消する機能です。

今回投稿した時間を投稿ページに反映させたく実装に至りました。

データの追加

postItem() {
      const id = firebase
        .firestore()
        .collection("posts")
        .doc().id;
      firebase
        .firestore()
        .collection("posts")
        .add({
          title: this.title,
          description: this.description,
          genre: this.genre,
          time: firebase.firestore.FieldValue.serverTimestamp(),
          id: id,
        });

Firestoreにデータを追加させる際に、今回はtimeという値を使って記載してみました。

time: firebase.firestore.FieldValue.serverTimestamp(),

上記のように記載するだけで投稿時間を追加してくれます。

データの取得

実は、serverTimestamp 自体は時刻情報を持ってなくて、
Firebase サーバー側でデータを保存する時にサーバーの時刻に置き換えるための目印でしかありません。

これをjavascriptのデータ型に置き換えて取得しなければなりません。

{{ list.time.toDate().toLocaleString() }}

上記のように記載してあげることでjavascriptのデータ型で取得し、
「20xx / xx /xx xx:xx:xx」という形で時刻表示させる事が可能です。

0
0
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
0
0