Home > Enterprise >  how to convert firebase time stamp to date angular
how to convert firebase time stamp to date angular

Time:09-30

typescipt

    public Patients: Observable<any>;
    constructor(private db: AngularFirestore) {
        this.Patients = this.db.collection('Patients').valueChanges();

// get data from firebase :

     ngOnInit(): void {
    this.Patients.subscribe((response) => {
      this.prepareData(response);
      this.console.log(response);
    });
  }

  

// in this section use for add data to apexcharts

      prepareData(patients) {
    
     patients.forEach((patient) => {
    
      });
      }

CodePudding user response:

I guess the firebase Timestamp is in ISO 8601 and thats not fully supported by the JavaScript Date method.

To convert it for further use you could try something like:

const firebaseDate = "20190412T131518.000Z";
const convertedDate = new Date(firebaseDate.replace(/(....)(..)(.....)(..)(.*)/, '$1-$2-$3:$4:$5'));
console.log(convertedDate);

EDIT just saw your comment reply you can simply pass the seconds to the date method

const firebaseObj = { seconds: 1612890000, nanoseconds: 0 }
const convertedDate = new Date(firebaseObj.seconds)

console.log(convertedDate)

CodePudding user response:

The firebase timestamp offers a toDate method that basically returns a Date object.

You can create some utility types and guards that might come in handy when dealing with Firestore records.

export interface FireTimeStamp extends Date {
    toDate: () => Date;
}

export type TimeStamp = Date | FireTimeStamp;

export const isFireStamp = (value: FireTimeStamp | Date | unknown): value is FireTimeStamp =>
    (value as FireTimeStamp)?.toDate && (value as FireTimeStamp)?.toDate() !== undefined;

export const isTimeStamp = (value: TimeStamp | unknown): value is TimeStamp =>
    isFireStamp(value) || value instanceof Date;

And here is a utility function for getting the date when you're not sure if it's a Date object or firebase time stamp object.

export const toDate = (date: TimeStamp): Date => isFireStamp(date) ? date.toDate() : date;

You can also have a custom pipe to convert the date if you need to display it.


@Pipe({
    name: 'toDate'
})
export class ToDatePipe implements PipeTransform {
    transform(date: TimeStamp): Date {
        return toDate(date);
    }
}
  • Related