function getJwtExpiration(token) {try {const base64Url = token.split('.')[1]; // 提取 payload 部分const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); // Base64Url 转换为 Base64const jsonPayload = decodeURIComponent(atob(base64).split('').map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));const payload = JSON.parse(jsonPayload);if (payload.exp) {// `exp` 通常是 UNIX 时间戳(秒)const expirationDate = new Date(payload.exp * 1000); // 转换为毫秒return expirationDate;} else {throw new Error("Token does not have an 'exp' field");}} catch (error) {console.error('Error parsing JWT:', error);return null;}
}// 示例用法
const jwtToken = "eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGR w";
const expiration = getJwtExpiration(jwtToken);if (expiration) {console.log(`Token expires at: ${expiration}`);
} else {console.log("Failed to retrieve expiration date.");
}