I have a function that converts date string to Date
JavaScript
x
5
1
const convertStringToDate = (string) => {
2
const fragments = string.split('/')
3
return new Date(fragments[2], fragments[1] - 1, fragments[0])
4
}
5
Then I use as following:
JavaScript
1
4
1
const birthdate = convertStringToDate('19/11/1986')
2
3
await reference.set({ birthdate })
4
But on firebase console, the birthdate is stored as an empty array as the image bellow:
What I am doing wrong?
Advertisement
Answer
convertStringToDate
returns a Date object, which if you console log, will show up something like this:
JavaScript
1
2
1
[object Date] { }
2
If you want to store it as a string, you need to convert that Date object to a string with something like birthdate.toIsoString()
. But because this is Firebase, if you want to store an actual date, you want to convert it to a Firestore timestamp:
JavaScript
1
6
1
// On the client
2
await reference.set({ birthdate: firebase.firestore.Timestamp.fromDate( birthdate ) })
3
4
// Or on the server
5
await reference.set({ birthdate: admin.firestore.Timestamp.fromDate( birthdate ) })
6
When you retrieve it later, you’d use:
JavaScript
1
6
1
// To get a date object
2
const birthdate = doc.data().birthdate.toDate()
3
4
// To get the date in milliseconds
5
const birthdate = doc.data().birthdate.toMillis()
6