如何使用AngularFire获取时间戳火库的YYYY/MM/DD



我从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.modulesdeclarations

最新更新