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 formatTime2 = 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].map(formatNumber).join('-') } const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } /** * 日期格式化 * @param {Object} date * @param {Object} fmt */ function dateFormat(date, fmt) { if (!date) { return } if (!fmt) { fmt = 'yyyy-MM-dd hh:mm' } if (!(date instanceof Date)) { date = new Date(typeof date == 'number' ? date : date.replace(/-/g, '/')) } if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)); } let o = { 'M+': date.getMonth() + 1, 'd+': date.getDate(), 'h+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds() }; for (let k in o) { if (new RegExp(`(${k})`).test(fmt)) { let str = o[k] + ''; fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : ('00' + str).substr(str.length)); } } return fmt; } module.exports = { formatTime: formatTime, formatTime2: formatTime2, dateFormat }