const debug = require('debug')('ultrong:dateformat'); module.exports = { dateFormat: (datestring, category = 'all') => { if (datestring === undefined || datestring == '') return ''; const date = new Date(datestring); const year = date.getFullYear(); const month = (parseInt(date.getMonth()) + 1) < 10 ? '0' + (parseInt(date.getMonth()) + 1).toString() : (parseInt(date.getMonth()) + 1); const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); const hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(); const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(); switch (category) { case 'all': return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes; case 'month-day': return month + '-' + day; case 'year-month-day': return year + '-' + month + '-' + day; case 'month-day hh:mm:ss': return month + ' - ' + day + ' ' + hour + ':' + minutes + ':' + seconds; case 'month-day hh:mm': return month + ' - ' + day + ' ' + hour + ':' + minutes; case 'difference': const newDate = new Date(); if (newDate.getFullYear() > year) return (newDate.getFullYear() - year) + '年前'; else if (newDate.getMonth() + 1 > month) return ((newDate.getMonth() + 1) - month) + '月前'; else if (newDate.getDate() > day) return (newDate.getDate() - day) + '天前'; else if (newDate.getHours() > hour) return (newDate.getHours() - hour) + '小时前'; else if (newDate.getMinutes() > minutes) return (newDate.getMinutes() - minutes) + '分钟前'; else if (newDate.getSeconds() > seconds) return (newDate.getSeconds() - seconds) + '秒前'; else return ''; default: return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds; } }, getDateString: () => { let date = new Date(); let year = date.getFullYear(); let month = date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth(); let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); return '_' + year + month + day; }, //将日期换算成今天的日期,时间不变 getTimeToToday: (date) => { let cdate = new Date(); const year = cdate.getFullYear(); const month = (parseInt(cdate.getMonth()) + 1) < 10 ? '0' + (parseInt(cdate.getMonth()) + 1).toString() : (parseInt(cdate.getMonth()) + 1); const day = cdate.getDate() < 10 ? '0' + cdate.getDate() : cdate.getDate(); const hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(); const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(); const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(); return new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds); } }