Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@exsrx97

Firebaseのタイムスタンプをいい感じの日付型へ変換

はじめに

Firebaseでデータにタイムスタンプを持たせることは多いが、そのデータをいい感じに表示させる方法

タイムスタンプ素材の型

まずタイムスタンプをそのままの型でコンソールに表示すると、一見不思議な数列が返ってくる

test.jsx
console.log(timestamp);

    => 063758775786.728000000

これをtoDate()で日付型に変換すると、何時なのか分かる型で返ってきたものの、このままアプリに表示するには少しブサイク

test.jsx
console.log(timestamp.toDate());

    => Wed Jun 09 2021 04:03:06 GMT+0900 (日本標準時)

いい感じに変換する関数を作る

test.jsx
const datetimeToString = (date) => {
  return date.getFullYear() + '-' 
  + ('00' + (date.getMonth() +1)).slice(-2) 
  + '-' + ('00' + date.getDate()).slice(-2)
  + ' ' + ('00' + date.getHours()).slice(-2)
  + ':' + ('00' + date.getMinutes()).slice(-2)
  + ':' + ('00' + date.getSeconds()).slice(-2)
}

この関数に日付型へ変換したタイムスタンプを引数として渡すと、、、

test.jsx
const date = datetimeToString(updated_at.toDate())
console.log(date);
     => 2021-06-09 04:03:06

よくある形へ変換できた!

おわりに

Firebaseのドキュメントは肌に合わない

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
exsrx97
備忘録

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?