【问题标题】:convert firestore timestamp to date into different format将firestore时间戳转换为不同的格式
【发布时间】:2020-02-04 11:15:09
【问题描述】:

时间戳变量存储在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 在控制台上显示“无效日期”

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    您应该使用 Firestore TimestamptoDate() 方法:

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

    返回Date

    表示与 this 相同时间点的 JavaScript Date 对象 时间戳,精确到毫秒。

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

    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>
    

    here 中可以找到使用moment.js 格式化日期的其他可能性。

    【讨论】:

    • 嗨@mayank3503,如果它解决了您的问题,您可以接受我的回答。谢谢。
    【解决方案2】:

    我想我知道发生了什么。

    您的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)
    

    干杯,

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 2020-02-23
      • 1970-01-01
      • 2021-09-17
      • 2011-09-18
      • 1970-01-01
      • 2021-01-18
      • 2015-09-08
      • 2016-11-26
      相关资源
      最近更新 更多