real answer => Wednesday, March 28-6ren">
gpt4 book ai didi

javascript - 在 JS 中将 Tick 转换为日期

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:22 25 4
gpt4 key购买 nike

我正在尝试检查 JWT token 的到期日期,但我尝试的所有方法都没有找到正确的日期。

"exp": 1522210228 => real answer => Wednesday, March 28, 2018 12:10:28 AM

我已经尝试了这些库,但我没有让它们工作...

  1. https://github.com/auth0/angular2-jwt/blob/master/src/jwthelper.service.ts
  2. https://github.com/auth0/jwt-decode

1

const helper = new JwtHelperService();
const decodedToken = helper.decodeToken(this.authentificationInfos.token);
const expirationDate = helper.getTokenExpirationDate(this.authentificationInfos.token);

console.log(expirationDate); => null?

2

import * as decode from 'jwt-decode';

const token = decode<{ data: { exp: number, iat: number, iss: string, nbf: number, username: string } }>(this.authentificationInfos.token);
const date = new Date(token.data.exp);
console.log(date); => Sun Jan 18 1970 09:50:10 GMT-0500 (Eastern Standard Time)

const d = new Date(0);
d.setUTCMilliseconds(token.data.exp);
console.log(d); => Sun Jan 18 1970 09:50:10 GMT-0500 (Eastern Standard Time)

这是完整的 token :

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoiYmlsb2RlYXV2aW5jZW50QG91dGxvb2suY29tIiwiaWF0IjoxNTIyMjA2NjI4LCJpc3MiOiJtbnAuY29tIiwibmJmIjoxNTIyMjA2NjI4LCJleHAiOjE1MjIyMTAyMjh9fQ.1WRlQatauXw2HEWj9B9VL6fIVR-4nAoKuWvkS4_m86k

https://jwt.io/正在解码 token ,显示的 exp 是正确的。

如何从 token.exp 获取真实日期?

最佳答案

JWT 中的时间戳是从 01.01.1970 00:00 UTC 开始计算的 UNIX 时间戳:https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4解释了数字日期用于 exp 声明(以及 nbf(不是之前)和 iat(发布于)声明)

https://www.rfc-editor.org/rfc/rfc7519#section-2定义数字日期:

A JSON numeric value representing the number of seconds from1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoringleap seconds.

var jwtDecode = require('jwt-decode');
var jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjp7InVzZXJuYW1lIjoiYmlsb2RlYXV2aW5jZW50QG91dGxvb2suY29tIiwiaWF0IjoxNTIyMjA2NjI4LCJpc3MiOiJtbnAuY29tIiwibmJmIjoxNTIyMjA2NjI4LCJleHAiOjE1MjIyMTAyMjh9fQ.1WRlQatauXw2HEWj9B9VL6fIVR-4nAoKuWvkS4_m86k";

const token = jwtDecode(jwt);
const d = new Date(0);
d.setUTCSeconds(token.data.exp);
console.log(d);

输出:

2018-03-28T04:10:28.000Z

使用 d.getHours()d.getMinutes() 等获取本地时间。

关于javascript - 在 JS 中将 Tick 转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49621097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com