如何使用 AngularFire 获取 YYYY/MM/DD 时间戳 firebase

How can I Get YYYY/MM/DD of Timestamp firebase with AngularFire

我从 firebase 得到这个对象,我想得到这个格式:2020-02-05。

t {seconds: 1601656203, nanoseconds: 529000000}
nanoseconds: 529000000
seconds: 1601656203
__proto__: Object

这是我的代码:

  public getAllUsers(): Observable<Users[]> {
    return this.afs.collection<Users>('Users', ref => ref.orderBy('createdAt'))
      .snapshotChanges()
      .pipe(
        map(actions =>
          actions.map(a => {
            const data = a.payload.doc.data() as Users;
            const docid = a.payload.doc.id;
            return { docid, ...data };
          })
        )
      );
  }

function toDateTime(secs) {
    var t = new Date(1970, 0, 1);
    t.setSeconds(secs);
    let year=t.getFullYear();
    let month=t.getMonth();
    let day=t.getDate()
    return year+"-"+less10(month)+"-"+less10(day);
}
function less10(time){
  return time<10 ? "0"+time :time;
}
console.log(toDateTime(1601656203))

如果您不在任何函数中使用日期,那么我建议您为此使用自定义管道。

  import { Pipe, PipeTransform } from '@angular/core';
   @Pipe({
      name: 'firebaseDate',
      pure: false
   })
    
   export class FireBaseTimePipe implements PipeTransform {
      transform(value: number): any {  
        var t = new Date(1970, 0, 1);       
        t.setSeconds(value);
        let year=t.getFullYear();
        let month=t.getMonth();
        let day=t.getDate()
        return year+"-"+this.less10(month)+"-"+this.less10(day);        
      }
      less10(time){
          return time<10 ? "0"+time :time;
      }
    }

并在 html

{{seconds |  firebaseDate}}

不要忘记添加到 app.modules declarations 这个管道