将秒添加到 JS 中的时间戳(React)

时间:2021-04-20 16:53:39

标签: javascript

对于应用程序,我使用的是 OAuth 令牌。在响应中,我得到了从现在到令牌过期的秒数。 所以我想拥有令牌不再好的时间戳。 我需要将此秒数添加到当前时间戳中。

我试过了,但这不会给我一个未来的时间戳:

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

1 个答案:

答案 0 :(得分:0)

据我所知,new Date().getTime() 没有问题。以下应该适用于您的情况:

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

带有一些 HMTL 的 Javascript 示例

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>

希望这个例子能帮到你(运行程序时查看整页)!

相关问题