firebase 将firestore时间戳转换为不同格式的日期

webghufk  于 2023-04-22  发布在  其他
关注(0)|答案(3)|浏览(258)

timestamp变量存储在firestore中,当提取时,它是秒和纳秒的格式,如何将timestamp转换为类似2018-09- 19 T00:00:00的格式

let Ref=firebase.firestore().collection("Recruiter").doc(u.uid).collection("Jobs")
    Ref.orderBy("timestamp", "desc").onSnapshot(function(snapshot){
      $.each(snapshot.docChanges(), function(){
        var change= this
        if(change.type==="added"){
           var ab= new Date(change.doc.data().timestamp) 
           console.log(ab)
          thisIns.RecruiterChart.chartOptions.xaxis.categories.push(
            ab
            ) 

           console.log( thisIns.RecruiterChart.chartOptions.xaxis.categories)
        }

      })
    })

变量ab在控制台上显示“无效日期”

83qze16e

83qze16e1#

您应该使用Firestore TimestamptoDate()方法:
将Timestamp转换为JavaScript Date对象。由于Date对象仅支持毫秒精度,因此此转换会导致精度损失。
返回Date
JavaScript Date对象,表示与此Timestamp相同的时间点,精度为毫秒。
因此,您可以执行以下操作:

var timestampDate = change.doc.data().timestamp.toDate(); 
console.log(timestampDate);

然后,您需要根据需要格式化此日期。最简单的方法是使用专用库,如moment.js,如下所示:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

// ...

<script>

   // ...

    var timestampDate = change.doc.data().timestamp.toDate(); 
    var m = moment(timestampDate );
    var mFormatted = m.format();    // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds) 
    console.log(mFormatted );

    // ...

</script>

使用moment.js化日期的其他可能性可以在这里找到。

qvtsj1bj

qvtsj1bj2#

我想我知道发生了什么。
你的ab变量应该是字符串格式的,对吗?
尝试先将其解析为Number ..然后看看会发生什么。
尝试记录如下内容:

var ab= new Date(Number(change.doc.data().timestamp))
console.log(ab)
thisIns.RecruiterChart.chartOptions.xaxis.categories.push(
  ab
) 

console.log( thisIns.RecruiterChart.chartOptions.xaxis.categories)

var ab= new Date(parseInt(change.doc.data().timestamp, 10))
console.log(ab)
thisIns.RecruiterChart.chartOptions.xaxis.categories.push(
  ab
) 
console.log( thisIns.RecruiterChart.chartOptions.xaxis.categories)

干杯

xj3cbfub

xj3cbfub3#

var ab = change.doc.data().timestamp.toDate().toLocaleDateString('en-US') // 7/2/2021
或更多:
var ab = change.doc.data().timestamp.toDate().toLocaleDateString('en-US', { weekday:"long", year:"numeric", month:"short", day:"numeric"})//2021年7月2日星期五
阅读更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

相关问题