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.
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.
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:
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
{{ 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With