繁体   English   中英

比较这两个时间戳我做错了什么?

[英]What i'm doing wrong comparing this two timestamps?

我将角度中的两个时间戳与意外结果进行比较。 这是我的代码:

public isAuthenticated(): boolean {

    const token = localStorage.getItem('Fakelife');
    const lifetime = new Date().getTime();
    const result = lifetime - token;
    const hoursDiff = result / (3600 * 1000);
    if ( hoursDiff > 3600 ) {
        //60 minutes were passed from start
        console.log('not expired');
        return true;
    } else {
        console.log('expired');
        return false;
    }
}

令牌的结果是= 1557167443251终身的结果是= 1557167505672 hoursDiff的结果是0.02560138888888889

如你所见,我只是想比较是否已经过了一个小时。 我做错了什么?

总是返回console.log('expired');

谢谢你的时间。

根据评论,这里是应该工作的代码,即使它在逻辑上可能不是最好的方式!

public isAuthenticated(): boolean {
    const token = localStorage.getItem('Fakelife'); //this returns a string
    const lifetime = new Date().getTime(); // current time in millis
    const result = lifetime - token; //difference between two times in millis
    const hoursDiff = result / (1000); //difference between two times in seconds
    if ( hoursDiff < 3600 ) { // if less than 3600 seconds, token is not expired
        //3600 seconds have not passed
        console.log('not expired');
        return true;
    } else {
        console.log('expired');
        return false;
    }
}

这是一种更简洁的方法。

public isAuthenticated(): boolean {
  return (new Date().getTime() - (1000 * 60 * 60) < parseInt(localStorage.getItem('Fakelife')));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM