【问题标题】:How to Subtract firebase timestamp with current time and check if it exceeds 5 minutes in Angular如何用当前时间减去firebase时间戳并检查它是否在Angular中超过5分钟
【发布时间】:2017-07-03 18:56:55
【问题描述】:

我有一个 Angular 应用程序,我在其中使用 firebase.database.ServerValue.TIMESTAMP 将记录存储到带有时间戳的 Firebase

现在我想检查添加到数据库的时间戳是否超过五分钟。

我尝试在我的组件中使用 moment ,但它只是不起作用。它正在提供虚假数据。我猜存储在 Firebase 中的数据是在我在印度的时代,所以如何让时刻在 Angular 中发挥作用。

我正在使用 Angular 2 Moment。

这是我试过的

import * as moment from 'moment/moment';

      edit(i:number){
        const val = moment.unix(this.comments[0].createdAt);// the value is a epoch time that is the standard that is stored in firebase
        const present = moment().unix();

        console.log(moment.duration(val.diff(present)));
      }

this.cmets在date中使用时的值

let ts = new Date(this.comments[0].createdAt * 1000); = 8 月 5 日星期三 49474 20:09:20 GMT+0530(印度标准时间)

就目前而言——2017 年 7 月 4 日星期二 14:56:46 GMT+0530(印度标准时间)

请帮助解释为什么它的 cmets 数据没有在 7 月 3 日的时间下沉,因为它是当天在 firebase 上添加的

【问题讨论】:

  • this.comments[0].createdAt的值是多少?
  • 这是一个存储在firebase中的纪元时间
  • 以毫秒(即 javascript 类型)或秒为单位?
  • 秒 unix 时间戳

标签: javascript angular momentjs angular2-moment


【解决方案1】:
const now = new Date();
const ts = new Date(this.comments[0].createdAt);
const diff = now.getTime() -  ts.getTime();

console.log(diff > 5 * 60 * 1000); // this will give you true or false

【讨论】:

    【解决方案2】:

    您可以使用 javascript Date 对象进行数学运算,即

    let now = new Date();
    let ts = new Date(this.comments[0].createdAt * 1000);
    let diff = now.getTime() - ts.getTime();
    
    console.log(diff > 5 * 60 * 1000);
    

    【讨论】:

    • 它的剂量显示了消息在最后一天存储的正确信息,但控制台 .log 仍然显示为假,因为它超过分钟应该说是正确的
    • 当我在控制台记录它们时 - 8 月 5 日星期三 49474 20:09:20 GMT+0530(印度标准时间),现在 - 2017 年 7 月 4 日星期二 14:56:46 GMT+0530(印度标准时间)时间)
    • 是的,因为当您记录一个日期对象时,它会将 toString() 应用于自身,这是一个人类可读的字符串,这就是您在 diff 中使用 .getTime() 以便它转换日期为毫秒
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2017-05-06
    • 2020-06-02
    • 1970-01-01
    • 2022-01-16
    • 2018-08-15
    相关资源
    最近更新 更多