Vue Firebase - convert array of firestore timestamp value to readable javascript date

Viewed 62

Im able to get document data from firestore collection as array and put them on view but dont know how to convert the timestamp value to readable date.

enter image description here

getDocs(collection(db, "timeoffreq"))
  .then((querySnapshot) => {
    const array = []
    querySnapshot.forEach((doc) => {
      array.push(doc.data())
    });
    timeoffreq.value = array
})
  
const timeoffreq = ref([{}])

And I just put it to view like this:

<tr v-for="(timeoffreq, timeoffreqIdx) in timeoffreq" :key="timeoffreq.uid" :class="timeoffreqIdx % 2 === 0 ? 'bg-white' : 'bg-gray-50'">
     <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
        {{ timeoffreq.type }}
     </td>
     <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
        {{ timeoffreq.desc }}
      </td>
     <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
        {{ timeoffreq.start }}
     </td>
     <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
        {{ timeoffreq.end }}
     </td>
     <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
     <a href="#" class="text-indigo-600 hover:text-indigo-900">Edit</a>
     </td>
</tr>

But the start and end field output show up like this:

Timestamp(seconds=1663174800, nanoseconds=0)

how do i convert start and end fields to readable date first?

I tried something like this:

var date = new Date(timeoffreq.start).toDateString()
console.log(date)

but the output: Invalid Date

1 Answers

You can use the Timestamp class to convert date field to Date object.

import firebase from "firebase/app"
const date = firebase.firestore.Timestamp(timeoffreq.start).toDate()

Or just simply use the seconds field to convert

const date = new Date(timeoffreq.start.seconds)
Related