18

I'm trying to get the timestamp of a document that I created in firestore, but what I get is this:

enter image description here

myService.ts

getDomiciliarios() {
this.domiciliarios = this.afs.collection('domiciliarios').snapshotChanges().map(actions => {
  return actions.map(a => {
    const data = a.payload.doc.data() as Domiciliario;
    const id = a.payload.doc.id;
    const date = firebase.firestore.FieldValue.serverTimestamp();
    return { id, ...data, date };
  });
});

return this.domiciliarios;
}

myComponent.ts

ngOnInit() {
const domiciliarios = this.fs.getDomiciliarios()
  .subscribe(data => this.dataSource.data = data, date => date);
}

myComponent.html

<ng-container matColumnDef="fecha">
  <mat-header-cell *matHeaderCellDef mat-sort-header> Fecha </mat-header-cell>
  <mat-cell *matCellDef="let domiciliario"> {{ domiciliario.date }} </mat-cell>
</ng-container>

How can I print that timestamp, should I have previously created it?

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Paco Zevallos
  • 2,165
  • 7
  • 30
  • 68

4 Answers4

23

IF you want the date value of firebase.firestore.FieldValue.serverTimestamp() you can use .toDate(). See FireStore Timesteamp. In your case it will be domiciliario.date.toDate() in your template.

Papa Kojo
  • 793
  • 8
  • 18
19

I think you are using FieldValue.serverTimestamp() the wrong way: as the documentation states, firebase.firestore.FieldValue methods return "values that can be used when writing document fields with set() or update()". (See https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue)

You are using the serverTimestamp() method while reading the data.

You should use it when you create the records in the database, as you mention at the end of your question.

EDIT: Do as follow:

const timestamp = firebase.firestore.FieldValue.serverTimestamp();
docRef.update({ updatedAt: timestamp });

You can then query like

collectionRef.orderBy('updatedAt').get()
    .then(snapshot => {
        snapshot.forEach(doc => {
            ...
        });
    })
    .catch(err => {
        console.log('Error getting documents', err);
    });

The above code is pure JavaScript and you may adapt it to angular and type script but the philosophy is the same.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
  • This timestamp is not generated automatically like the ID? If not, then how can I add that timestamp in Firestore? – Paco Zevallos Apr 25 '18 at 14:13
  • Thanks I added a variable with `firebase.firestore.FieldValue.serverTimestamp ();` and this added a field with the date in Firestore. I will respond with this. – Paco Zevallos Apr 25 '18 at 16:18
  • @PacoZevallos Cool! :-) If you now query ordered on this value you should get what you are looking for – Renaud Tarnec Apr 25 '18 at 16:22
  • I should mention that `new Date ()` also works for me, I do not understand what the difference is with `firebase.firestore.FieldValue.serverTimestamp ()` when creating a timestamp but it also works for me. – Paco Zevallos Apr 25 '18 at 16:47
  • @PacoZevallos `new Date()` is the current timestamp of your client machine (the user's browser) while `firebase.firestore.FieldValue.serverTimestamp ()` is the timestamp of the Firebase server – Renaud Tarnec Apr 25 '18 at 16:55
  • Oh that's a very significant difference then, since `new Date` can be manipulated and modified by the user, whereas `firebase.firestore.FieldValue.serverTimestamp ()` does not. This is correct? – Paco Zevallos Apr 25 '18 at 16:59
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/169783/discussion-between-renaud-tarnec-and-paco-zevallos). – Renaud Tarnec Apr 25 '18 at 17:00
  • has this changed to "FirebaseFirestore.FieldValue.serverTimestamp(),"? because I am getting instance of FirebaseFirestore instead of firebase.firestore? Kindly confirm or suggest me. Thanks. – Kamlesh Jun 15 '21 at 13:48
  • @Kamlesh AFAI it is still the same syntax **in JavaScript**. – Renaud Tarnec Jun 15 '21 at 13:51
  • Could you please suggest me for flutter / dart for the same? Thanks. – Kamlesh Jun 15 '21 at 13:58
  • @Kamlesh See https://pub.dev/documentation/cloud_firestore/latest/cloud_firestore/FieldValue-class.html – Renaud Tarnec Jun 15 '21 at 14:30
17

If you want the current Date as a timestamp you can use the following

For Firebase Functions

import admin = require('firebase-admin');

const todayAsTimestamp = admin.firestore.Timestamp.now()

For local projects

import { Timestamp } from '@google-cloud/firestore';

const myTimestampAsDate = Timestamp.now()
Ruan
  • 3,969
  • 10
  • 60
  • 87
  • 2
    This returns user's local date time. If user's date/time is wrong, you will get wrong date/time – fyelci Apr 18 '21 at 01:50
2

Thanks to @Renaud who put emphasis on where I was implementing the timestamp, it should be when creating a record in Firestore. In my case I am working with a formGroup, then the code would look something like this:

forma: FormGroup;

constructor( fb: FormBuilder) { 
  this.forma = fb.group ({
    field1: [ ''],
    field2: [ ''],
    ...
    myDate: [ firebase.firestore.FieldValue.serverTimestamp() ],
  });
}

This alternative also works but remember that it is the current time of the client's computer (user's browser).

forma: FormGroup;

constructor( fb: FormBuilder) { 
  this.forma = fb.group ({
    field1: [ ''],
    field2: [ ''],
    ...
    myDate: [ new Date() ],
  });
}
Paco Zevallos
  • 2,165
  • 7
  • 30
  • 68