簡體   English   中英

Firebase 格式化日期的 firestore 時間戳

[英]Firebase firestore timestamp to Formatted Date

我正在做一個 firebase 項目,為了顯示時間和實體,我得到的是時間戳。 我正在做一個 React Native 項目。 如何將接收到的時間戳轉換為格式正確的日期。 這是時間戳:

在此處輸入圖像描述

我在this.props.time中有這個時間,所以我嘗試this.props.time.toDate()但我得到的是一個錯誤。 Invariant Violation:Objects are not valid as a React child(found: Tue Nov 26 2019 11:51:58 GMT+05:30(Indian Standard Time))

您可以使用new Date(time.seconds * 1000 + time.nanoseconds/1000000)創建一個Date 對象,然后按照您想要的方式操作它。

如果您從文檔中檢索數據,您可以這樣做:

// time.toDate()
convertDate(doc.data().time.toDate())

const convertDate = (date) => {
    // whatever formatting you want to do can be done here
    var d = date.toString()
    return d.substr(0, 21);
}

您可以使用https://momentjs.com/來顯示

{moment(yourTimestamp.toDate()).format( ****format 在上面的鏈接內)}

正確: new Date(time.seconds * 1000 + time.nanoseconds/1000000)

不正確: new Date(time.seconds * 1000 + time.nanoseconds/1000)

因為, 在此處輸入圖片說明

對於 firestore v9,您可以簡單地這樣做。

您可以使用 toDate() function 和 toDateString() 一起單獨顯示日期部分。

const date = dateCreated.toDate().toDateString()
//Example: Friday Nov 27 2017

假設您只需要時間部分,那么使用 toLocaleTimeString()

const time = dateCreated.toDate().toLocaleTimeString('en-US')
//Example: 01:10:18 AM, the locale part 'en-US' is optional

假設您需要從日期中提取月份和日期。

你只需這樣做:

const date = new Date(Date.now());
date.toLocaleString('en-US', {month: 'short'}); // {month:'long'}
Expected Output: "Jan"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM