Using Firebase Timestamp with Angular Bootstrap’s Datepicker

Idan Cohen
Dec 21, 2018 · 2 min read

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… :-)

Idan Cohen

Written by

Client Architect @ UVeye

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade