/** * 日期时间格式化 * 2018/01/01 23:59:59 */ 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(':') } /** * 日期时间格式化 * 2018-01-01 23:59:59 */ 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, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':') } /** * 对个位数前补零 */ const formatNumber = n => { n = n.toString() return n[1] ? n : '0' + n } /** * 日期格式化 * 2018-01-01 */ const formatDate = 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(':') } /** * 时间格式化 * 23:59:59 */ const formatTimeTwo = date => { const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return [hour, minute, second].map(formatNumber).join(':') } /** * 路径格式化 */ const formatUrl = (url, obj) => { let temp = [] let fn = (obj) => { let temp = [] for (let i in obj) { if (obj[i] != null && typeof obj[i] == 'object') { temp.push(`${i}=${JSON.stringify(obj[i])}`) } else { temp.push(`${i}=${obj[i]}`) } } return temp.join('&') } return url.indexOf('?') < 0 ? url + '?' + fn(obj) : url + '&' + fn(obj) } /** * 函数节流和函数抖动。 */ function throttle(fn, gapTime) { if (gapTime == null || gapTime == undefined) { gapTime = 1500 } let _lastTime = null // 返回新的函数 return function () { let _nowTime = + new Date() if (_nowTime - _lastTime > gapTime || !_lastTime) { fn.apply(this, arguments) //将this和参数传给原函数 _lastTime = _nowTime } } } module.exports = { formatTime, formatTime2, formatUrl, formatDate, formatTimeTwo, formatNumber, throttle }