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

5

时间戳变量存储在Firestore中,当提取时,它的格式为秒和纳秒,如何将时间戳转换为类似于2018-09-19T00: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在控制台上显示为"无效日期"

3个回答

7
你应该使用Firestore的Timestamp对象中的toDate()方法:

将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 格式化日期的其他可能性可在 这里 找到。


1
我想我知道发生了什么。
您的ab变量应该是字符串格式,对吧?
首先尝试将其解析为数字,看看会发生什么。
尝试记录类似以下内容的东西:
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)

干杯,


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接