const formatTime = (date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); return ( [year, month, day].map(formatNumber).join("/") + " " + [hour, minute, second].map(formatNumber).join(":") ); }; const formatNumber = (n) => { n = n.toString(); return n[1] ? n : "0" + n; }; // 用法 timeStr('YYYY-MM-DD hh:mm:ss') => '2018-3-22 12:12:12' // 用法 timeStr('hh:mm:ss') => '12:12:12' // 也可使用第二参数格式化指定时间 // timeStr('YYYY-MM-DD hh:mm:ss', '2018-3-22 12:12:12') => '2018-3-22 12:12:12' export function timeStr(time, type = "YYYY-MM-DD hh:mm") { let data = time ? new Date(time - 0) : new Date(); let year = data.getFullYear(); let month = data.getMonth() + 1 >= 10 ? data.getMonth() + 1 : "0" + (data.getMonth() + 1); let day = data.getDate() >= 10 ? data.getDate().toString() : "0" + data.getDate(); let hour = data.getHours() >= 10 ? data.getHours().toString() : "0" + data.getHours(); let minutes = data.getMinutes() >= 10 ? data.getMinutes().toString() : "0" + data.getMinutes(); let seconds = data.getSeconds() >= 10 ? data.getSeconds().toString() : "0" + data.getSeconds(); return type .replace("YYYY", year) .replace("MM", month) .replace("DD", day) .replace("hh", hour) .replace("mm", minutes) .replace("ss", seconds); } module.exports = { formatTime: formatTime, timeStr, };