Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to timestamp for storing into firebase firestore in javascript

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.

number

I would like to have it inserted as shown below (as a timestamp, not as a number).

enter image description here

Is this possible?

like image 746
Arjen de Jong Avatar asked Nov 26 '18 14:11

Arjen de Jong


People also ask

How do I convert a firestore date timestamp to a JS date ()?

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.

How do you post a timestamp on firestore?

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.

What format is firestore timestamp?

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.

How do I display Firebase timestamp?

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));


2 Answers

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

like image 185
Sean Stayns Avatar answered Sep 21 '22 17:09

Sean Stayns


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.

like image 24
Doug Stevenson Avatar answered Sep 18 '22 17:09

Doug Stevenson