LoginSignup
6
1

More than 1 year has passed since last update.

Firebase(Firestore) Timestamp型の取得と表示方法

Posted at

Firestoreに保存されているTimestamp型のデータの取得と表示方法についてまとめます。

データ構造

  • コレクション名:posts
  • ドキュメントID:自動(ランダム)
  • フィールド
    • title (string)
    • createdAt (timestamp)

Day.jsインストール

「Day.js」は「Moment.js」とほぼ互換性のあるAPIを提供しており、Moment.jsの代わりとして推奨されている日付操作用ライブラリの1つ。

npm install day.js --save

// 確認
npm list --depth=0 | grep dayjs

日付形式での取得と表示

timestamp型をそのまま取得すると以下のようなオブジェクトになる

createdAt: t {seconds: 1618557497, nanoseconds: 367000000}

日付形式に変換するには、dayjsのtoData() メソッドを使う
またformat()メソッドで形式を指定する

const [posts, setPosts] = useState([]);

  useEffect(() => {
    const postData = collection(db, "posts");

    onSnapshot(postData, (querySnapshot) => {
      const data = QuerySnapshot.docs.map((doc)=>({
          id: doc.id,
          title: doc.data().title
          // 日付取得
          createdAt: dayjs(doc.data().createdAt.toDate()).format('YYYY/MM/DD'),
      }))
      setPosts(data);
    });
  }, []);

  return (
    <div className="App">
      <div>
        {posts.map((post) => (
          <div key={post.title}>
            <h1 className="title">{post.title}</h1>
            <p>{post.createdAt}</p>
          </div>
        ))}
      </div>
    </div>
 );

// 表示結果例
// 2022/05/31
6
1
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
6
1