Convert date to timestamp for storing into firebase firestore in javascript
You can simply use the following line:
var myTimestamp = firebase.firestore.Timestamp.fromDate(new Date());
.fromDate
is a static method from the static Timestamp class from Firebase.
Ref: Firebase Timestamp Doc
Update:
For cloud functions look at JGuo's comment:
If you are writing cloud functions, it becomes
admin.firestore.Timestamp.fromDate()
– JGuo Jan 21 at 1:56
If you want to store a field as a timestamp in Firestore, you'll have to send a JavaScript Date object or a Firestore Timestamp object as the value of the field.
If you want to use Date, simply say new Date(x)
where x
is the value in milliseconds that you were trying to add before.
If you want to use Timestamp, you would have to do more work to get that x
converted into a combination of seconds and nanoseconds to pass to the constructor, as the documentation suggests.
I solved it by using:
const created = firebase.firestore.Timestamp.fromDate(new Date()).toDate();
You have to import firebase from 'firebase/app'
explicitly in your code.
import * as firebase from 'firebase/app'
Make sure your created
or whatever constant is in type Date
before actually being saved to firestore.