Javascript 如何使用vue Js将firestore时间戳转换为完整日期

Javascript 如何使用vue Js将firestore时间戳转换为完整日期,javascript,firebase,vue.js,Javascript,Firebase,Vue.js,我想在vueApp中将从Google firestore获得的时间戳转换为天和月 我得到一个像这样的对象{秒:1549843200,纳秒:0} <template> <div v-for="note in notes" :key="note.id" class="note"> <div class="note_dates"> <span class="day">{{note.day}}</span>

我想在vueApp中将从Google firestore获得的时间戳转换为天和月

我得到一个像这样的对象{秒:1549843200,纳秒:0}

<template>
   <div v-for="note in notes" :key="note.id" class="note">
     <div class="note_dates">
       <span class="day">{{note.day}}</span>
       <span class="month">{{note.month}}</span>
       .........
</template>

<script>
export default {
  data() {
    return {
      notes: []
    };
  },

  methods: {},
  created() {
    notesCollection.get().then(querySnapshot => {
      querySnapshot.forEach(doc => {
        const query = {
          id: doc.id,
          content: doc.data().content,
          day: doc.data().created_on,
          month: doc.data().created_on
        };

        this.notes.push(query);
      });
    });
  }

{{note.day}
{{note.month}
.........
导出默认值{
数据(){
返回{
注:[]
};
},
方法:{},
创建(){
notesCollection.get().then(querySnapshot=>{
querySnapshot.forEach(doc=>{
常量查询={
id:doc.id,
内容:doc.data().content,
日期:创建日期为,
月份:已在上创建文档数据()
};
this.notes.push(查询);
});
});
}
在上创建的值是firestore集合中的时间戳


因此,在我的视图组件中,我只想回显时间戳中的日期和月份。

从时间戳中获取
秒值,乘以1000得到ms值,然后使用
日期()

let timestamp={秒:1549843200,纳秒:0}//firebase数据
让myDate=新日期(timestamp.seconds*1000)//日期对象

console.log(myDate)
只是为了补充上面Daniel的答案……有几个日期库……我觉得非常有用

例如:

import moment from "moment"

let myDate = created_on.seconds * 1000 // Unix ms timestamp

let myDay = moment(myDate, 'x').format('dddd') // Monday
let myMonth = moment(myDate, 'x').format('MMM') // January


这里

我认为您的用例不需要任何外部库。Firestore时间戳有一个返回日期对象的方法,因此您可以做的是:

  • 将时间戳转换为日期对象:

     const query = {
      id: doc.id,
      content: doc.data().content,
      date: doc.data().created_on.toDate()
    };
    
  • 使用内置日期方法获取数字日和月:
  • {{date.getDate()}}
    {{date.getMonth()+1}}

    月份从0开始计算,所以12月是11

    如果您想以不同的格式设置日期,我会首先尝试是否可以使用Intl.DateTimeFormat。如果这不能提供您需要的内容,我会从date fns中选择满足您需要的内容


    有多个具有不同时间戳的文档