时间戳UTC时区日期格式
⏱️ 什么是Unix时间戳?
Unix时间戳(Unix Time / Epoch Time)是自 1970-01-01 00:00:00 UTC 起,所经历的秒数(或毫秒数)。
- 秒级时间戳:如
1696060800 - 毫秒级时间戳:如
1696060800000
注意:时间戳不包含时区信息,本质上是 UTC 原点的偏移量。
🔄 时间戳与日期互转
JavaScript
// 秒 → 日期(本地时区)
const sec = 1696060800;
const dateFromSec = new Date(sec * 1000);
// 毫秒 → 日期
const ms = 1696060800000;
const dateFromMs = new Date(ms);
// 日期 → 秒/毫秒
const now = new Date();
const toSec = Math.floor(now.getTime() / 1000);
const toMs = now.getTime();
// 指定时区格式化(Intl)
const fmt = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit'
});
console.log(fmt.format(dateFromMs));
Python
from datetime import datetime, timezone
# 秒 → 日期(UTC)
sec = 1696060800
dt_utc = datetime.fromtimestamp(sec, tz=timezone.utc)
# 日期 → 秒
now_sec = int(datetime.now(tz=timezone.utc).timestamp())
🌍 UTC、本地时区与夏令时
- 存储与传输:优先使用 UTC(避免歧义)。
- 显示与交互:按用户时区显示(尊重本地化)。
- 夏令时:避免“本地时间加减”计算,使用时间库按时区转换。
🧪 常见坑位
- 混淆秒与毫秒:前端多为毫秒、部分后端接口用秒。
- 字符串解析的时区:如
2025-10-01 00:00:00默认当作本地或UTC?需明确约定。 - 批量转换的性能:对大批量记录,批量格式化需注意性能与缓存。
🧰 模板化格式化
常见格式:
YYYY-MM-DD HH:mm:ss
YYYY/MM/DD
YYYY-MM-DDTHH:mm:ssZ (ISO 8601, UTC)
// 简易格式化
function pad(n) { return n.toString().padStart(2, '0'); }
function formatYYYYMMDDHHmmss(d) {
const Y = d.getFullYear();
const M = pad(d.getMonth() + 1);
const D = pad(d.getDate());
const h = pad(d.getHours());
const m = pad(d.getMinutes());
const s = pad(d.getSeconds());
return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}
🔗 相关工具
需要快速进行时间戳 ↔ 时间互转、支持秒/毫秒与各时区?试试 Unix时间戳转换,支持批量转换与自定义格式。