Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert firestore TIMESTAMPS to full dates with vue Js

I want to convert the timestamp I get from the Google firestore to days and months in my vueApp.

I get an object like this Object { seconds: 1549843200, nanoseconds: 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);
      });
    });
  }

the value created_on is a timestamp in the firestore collection

So, in my view component, I want to echo just the day and the month from the timestamp.

like image 609
foliwe83 Avatar asked Dec 08 '22 12:12

foliwe83


2 Answers

Take the seconds value from the timestamp, multiply by 1000 to get the ms value, and use Date():

  let timestamp = { seconds: 1549843200, nanoseconds: 0 } // firebase data     
  let myDate = new Date(timestamp.seconds * 1000) // date object
  
  console.log(myDate)

From there, you can extract the month/day/year or otherwise format the date exactly as you would any other javascript Date object.

like image 186
Daniel Beck Avatar answered Dec 11 '22 09:12

Daniel Beck


I don't think you'll need any external libraries for your use case. Firestore timestamps have a method that returns a date object, so what you could do is:

  1. convert timestamp to date object:

     const query = {
      id: doc.id,
      content: doc.data().content,
      date: doc.data().created_on.toDate()
    };
    

https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#todate

  1. Use built-in Date methods to get the numerical day and month:

{{ date.getDate() }} and {{ date.getMonth() + 1 }}

Months start counting from 0, so december is 11

If you want to format the date differently, I'd first try if you can use Intl.DateTimeFormat. If that doesn't offer what you need I'd pick something from date-fns that meets your needs.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

https://date-fns.org/

like image 41
Thomas Kuhlmann Avatar answered Dec 11 '22 09:12

Thomas Kuhlmann