我的用户有:id、用户名、密码、 token 过期日期。当我生成 token 时,我生成一个字符串,如何检查 token 是否未过期?
最佳答案
java.time
请使用 java.time(现代 Java 日期和时间 API)来进行日期和时间工作。
public class User {
private String username;
private String password;
private Instant tokenExpires;
// constructor, getters, setters
public boolean isTokenExpired() {
return ! Instant.now().isBefore(tokenExpires);
}
}
Date
的现代替代品是 Instant
。这是一个时间点。
如果您无法更改 User
类并且 getTokenExpires()
返回老式的 Date
对象:
Instant tokenExpires = yourUser.getTokenExpires().toInstant();
if (Instant.now().isBefore(tokenExpires)) {
System.out.println("Token has not expired");
} else {
System.out.println("Token has expired");
}
链接: Oracle tutorial: Date Time解释如何使用 java.time。
关于java - java中如何检查token是否过期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61062003/