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

may*_*503 5 javascript firebase google-cloud-platform google-cloud-firestore

时间戳变量存储在 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)
        }

      })
    })
Run Code Online (Sandbox Code Playgroud)

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

Ren*_*nec 8

您应该使用toDate()Firestore 的方法Timestamp

将时间戳转换为 JavaScript 日期对象。此转换会导致精度损失,因为 Date 对象仅支持毫秒精度。

退货Date

JavaScript Date 对象表示与此 Timestamp 相同的时间点,精度为毫秒。

因此,您将执行以下操作:

var timestampDate = change.doc.data().timestamp.toDate(); 
console.log(timestampDate);
Run Code Online (Sandbox Code Playgroud)

然后,您需要根据需要设置该日期的格式。最简单的方法是使用专用库,例如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>
Run Code Online (Sandbox Code Playgroud)

可以在此处moment.js找到格式化日期的其他可能性。