前端開發中頻繁需要將日期對象或字符串轉為緊湊格式(如 yyyyMMddHHmmss)。本文提供三種不同場景的解決方案。
var s = '2016-06-06 12:05:35';
s = s.replace(/[- :]/g, ''); // "20160606120535"
function addZero(v) { return v < 10 ? '0' + v : v.toString(); }
var d = new Date();
var s = d.getFullYear().toString() +
addZero(d.getMonth() + 1) +
addZero(d.getDate()) +
addZero(d.getHours()) +
addZero(d.getMinutes()) +
addZero(d.getSeconds());
console.log(s); // 如 "20240115143025"
// 使用 toISOString 切片(UTC 時間)
new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
// 或使用 Intl.DateTimeFormat 組裝(本地時間)
const fmt = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
}).formatToParts(new Date()).reduce((acc, p) => acc + p.value, '');
根據項目兼容性要求選擇:簡單場景用正則替換,生產環境建議封裝統一工具函數。