1
0

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 1 year has passed since last update.

firebase firestoreに日付データを登録する方法

Posted at
const nowDate = Date.now();

これだとミリ秒で表示されてしまうため、フォーマットを変更します

ライブラリをインストールします

npm install date-fns
<script>
import { format } from 'date-fns'

methods: {
      submitPost: async function() {
        const db = getFirestore();
        const nowDate = Date.now();
        const myShaped = format(nowDate, "yyyyMMddHHmmss");
        const docRef = await addDoc(collection(db, "sample"), {
          commentTime: myShaped,
        });
        console.log("docref.id",docRef.id)
        }
    }
<script>

もし日付で並べ替えたい時は nowDateも設定しておきます。

<script>
import { format } from 'date-fns'

methods: {
      submitPost: async function() {
        const db = getFirestore();
        const nowDate = Date.now();
        const myShaped = format(nowDate, "yyyyMMddHHmmss");
        const docRef = await addDoc(collection(db, "sample"), {
          commentTime: myShaped,
          createdt: nowDate
        });
        console.log("docref.id",docRef.id)
        }
    }
<script>

表示する際

const displayQ = query(collection(db, "comments"),where("displayAccount", "==", this.routeId),orderBy("createdAt"));

このようにorderByとwhereを異なるフィールドで使用したい場合もあると思います。

この際は複合フィールドを設定しましょう。

これで問題なく設定できると思います。

最後にこの記事で間違った箇所や、足りない情報、やってもできなかったなどあれば気軽にコメントやTwitterで連絡ください。

Twitter

参考
https://firebase.google.com/docs/firestore/query-data/order-limit-data?hl=ja

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?