/** * 时间戳转时间字符串 * @param timestamp * @returns {string} */ function timestampToTime(timestamp) { timestamp = timestamp.toString().length === 10 ? timestamp * 1000 : timestamp; let date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000 let Y = date.getFullYear() + '-'; let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; let D = date.getDate() + ' '; let h = date.getHours() + ':'; let m = date.getMinutes() + ':'; let s = date.getSeconds(); return Y+M+D+h+m+s; } /** * 时间字符串转时间戳 * @param timeStr * @param isSecond * @returns {number} */ function timeStrToTimeStamp(timeStr,isSecond){ let date = new Date(timeStr); if(isSecond){ return date.getTime()/1000; }else{ return date.getTime(); } } /** * 时间戳转时间字符串 * @param time 时间戳 * @param format 格式 yyyy-MM-dd HH:mm:ss * @returns {*} 格式化后的时间字符串 */ function timeFormat(time, format) { let t = new Date(time); let tf = function(i) { return (i < 10 ? '0' : '') + i }; return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) { switch (a) { case 'yyyy': return tf(t.getFullYear()); break; case 'MM': return tf(t.getMonth() + 1); break; case 'mm': return tf(t.getMinutes()); break; case 'dd': return tf(t.getDate()); break; case 'HH': return tf(t.getHours()); break; case 'ss': return tf(t.getSeconds()); break; } }) } function getUnixTimeStamp(){ return Math.round(new Date().getTime()/1000); } module.exports = { timestampToTime, timeStrToTimeStamp, timeFormat, getUnixTimeStamp }