简体   繁体   English

在 JS 中为时间戳添加秒数(React)

[英]Add seconds to a timestamp in JS (React)

For an app, I'm using a OAuth token.对于应用程序,我使用的是 OAuth 令牌。 In the response, I get the number of seconds until the token expires from now.在响应中,我得到了令牌从现在开始过期的秒数。 So I want to have the timestamp where the token is not good anymore.所以我想拥有令牌不再好的时间戳。 I need to add this number of seconds to the current timestamp.我需要将此秒数添加到当前时间戳。

I tried this but this don't give me a future timestamp:我试过了,但这并没有给我未来的时间戳:

let now = new Date().getTime(); <-- CURRENT TIMESTAMP
let expiresIn = body.expires_in; <-- NUMBER OF SECONDS UNTIL THE TOKEN EXPIRES
let timestampWhereTokenExpires = now + expiresIn; <-- TIMESTAMP WHERE THE TOKEN EXPIRES BUT IT GIVES ME THE CURRENT TIMESTAMP

There is no problem with new Date().getTime() as far i know.据我所知, new Date().getTime()没有问题。 Following should work in your case:以下应该适用于您的情况:

let expiresInMS = 60000;    // let say expiration in 60 s / 1 min
let now = new Date();
let expiresDateTime = new Date(now.getTime() + expiresInMS);

Example in Javascript with some HMTL Javascript 中带有一些 HMTL 的示例

 function computeExpired(){ let expiresInMS = 60000; // let say expiration in 60 s / 1 min let now = new Date(); let expiresDateTime = new Date(now.getTime() + expiresInMS); // populate values to HTML elements document.getElementById('now').innerHTML = now.toLocaleString(); document.getElementById('expiresDateTime').innerHTML = expiresDateTime.toLocaleString(); // console logging console.log(now.toLocaleString()) console.log(expiresDateTime.toLocaleString()); }
 <:DOCTYPE html> <html> <body> <h3>Compute Expiration Date </h3> <p>let say expiration should occure in 60 s / 1 min from now:</p> <button onclick="computeExpired()">START</button> <br> <p>Now is: <p id="now"></p></span> <p>Will expire at: <p id="expiresDateTime"></p> </body> </html>

Hopefully, this example helps you out (view full page when running the program)!希望这个示例可以帮助您(运行程序时查看完整页面)!

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

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