在TypeScript和Node中计算24小时内两个Unix时间戳的剩余过期时间
TypeScript + Node 环境计算Unix时间戳剩余时长方案
前置注意事项
示例给出的两个时间戳存在单位差异:
current_time为13位毫秒级Unix时间戳,exp_time为带前导零的10位秒级Unix时间戳,计算前需要统一单位、处理无效前导零避免误差。
完整实现代码
/** * 计算距离过期的剩余时长,返回时分秒格式化字符串 * @param currentTime 当前时间戳,支持10位秒级/13位毫秒级,支持数字/字符串类型 * @param expTime 过期时间戳,支持10位秒级/13位毫秒级,支持数字/字符串类型 * @returns 格式化后的剩余时长,已过期则返回提示 */ function getRemainingTime(currentTime: number | string, expTime: number | string): string { // 统一转成数字类型,处理前导零问题 const current = Number(currentTime) const exp = Number(expTime) if (isNaN(current) || isNaN(exp)) { return '时间戳格式无效' } // 统一转成毫秒级时间戳 const currentMs = String(current).length === 10 ? current * 1000 : current const expMs = String(exp).length === 10 ? exp * 1000 : exp // 计算差值 const diff = expMs - currentMs if (diff <= 0) { return '已过期' } // 转换为时分秒 const totalSeconds = Math.floor(diff / 1000) const hours = Math.floor(totalSeconds / 3600) const minutes = Math.floor((totalSeconds % 3600) / 60) const seconds = totalSeconds % 60 // 补前导零美化输出 const padZero = (num: number) => num.toString().padStart(2, '0') return `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}` } // 示例测试 const current_time = 1633115367891 const exp_time = 1633201203 // 去掉无效前导零 console.log(getRemainingTime(current_time, exp_time)) // 输出:23:50:35
代码说明
- 兼容处理:支持传入10位秒级/13位毫秒级的时间戳,同时支持数字、字符串两种入参类型,自动处理前导零格式问题
- 边界校验:自动校验入参有效性,过期时间小于等于当前时间时直接返回已过期提示
- 格式美化:不足两位的时分秒自动补前导零,输出标准的
HH:mm:ss格式
运行方式
在Node环境下直接运行编译后的JS文件,或者使用ts-node直接运行TS文件即可得到结果。
内容的提问来源于stack exchange,提问作者Supez38
相关产品推荐
相关产品推荐

