Using Firebase Timestamp with Angular Bootstrap’s Datepicker
Firestore, the cloud database service by Google’s Firebase, recently announced that dates stored in its documents will be retrieved by default as Timestamps.
Timestamp is a javascript object with two properties: seconds
and nanoseconds
. It also comes with a few helpful methods: fromDate()
, toDate()
and now()
.
This change requires quite a few adjustments in the way your app handles dates. One of which is the implementations of Angular Bootstrap’s Datepicker. Luckily, ng-bootstrap offers a very convenient adapter to handle conversion between any custom date, and the ng-bootstrap’s native date structure.
To implement this adapter, create a new file called ngb-date-firestore-adapter.service.ts
-
import { Injectable } from '@angular/core';
import { NgbDateAdapter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { firestore } from 'firebase';
/**
* NgbDateAdapter implementation that allows using Firebase Firestore TimeStamp as a user date model.
* https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
*/
@Injectable()
export class NgbDateFirestoreAdapter extends NgbDateAdapter<firestore.Timestamp> {
/**
* Converts Firestore TimeStamp to a NgbDateStruct
*/
fromModel(ts: firestore.Timestamp): NgbDateStruct {
if (ts instanceof firestore.Timestamp) {
return {
year: ts.toDate().getFullYear(),
month: ts.toDate().getMonth() + 1,
day: ts.toDate().getDate()
};
} else return null;
}
/**
* Converts a NgbDateStruct to a Firestore TimeStamp
*/
toModel(ngbDate: NgbDateStruct): firestore.Timestamp {
const jsDate = new Date(
ngbDate.year ? ngbDate.year : new Date().getFullYear(),
ngbDate.month ? ngbDate.month - 1 : new Date().getMonth() - 1,
ngbDate.day ? ngbDate.day : new Date().getDate(),
12
);
return firestore.Timestamp.fromDate(jsDate);
}
}
Then edit you app.module (or wherever you import NgbModule
into your project) and add add this line your modules provider
array -
providers: [
{ provide: NgbDateAdapter, useClass: NgbDateFirestoreAdapter }
]
Now you can attach any Timestamp property to a Datepicker field.
Check full demo -
Any questions? Corrections? Please comment… :-)