I'm currently using Math.floor(Date.now() / 1000)
to get the correct timestamp format to add into a document in Firebase, however, the timestamp gets inserted as a number, and not as a timestamp.
I would like to have it inserted as shown below (as a timestamp, not as a number).
Is this possible?
To convert a Firestore date or timestamp to a JavaScript Date, we use firebase. firestore. Timestamp. fromDate to convert the a date to a Firestore timestamp.
So, you first need to convert it to native js Date object and then you can perform methods on it like toISOString() . Store as unix timestamp Date. now , it'll be stored as number i.e. 1627235565028 but you won't be able to see it as readable Date in firestore db.
firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.
To convert Firebase timestamp to date and time with JavaScript, we use the Date constructor. const timestamp = { nanoseconds: 0, seconds: 1562524200 }; console. log(new Date(timestamp. seconds * 1000));
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.
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