1 /** 2 * Parse the time to string 3 * @param {(Object|string|number)} time 4 * @param {string} cFormat 5 * @returns {string | null} 6 */ 7 export function parseTime(time, cFormat) { 8 if (arguments.length === 0 || !time) { 9 return null 10 } 11 const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' 12 let date 13 if (typeof time === 'object') { 14 date = time 15 } else { 16 if ((typeof time === 'string')) { 17 if ((/^[0-9]+$/.test(time))) { 18 // support "1548221490638" 19 time = parseInt(time) 20 } else { 21 // support safari 22 // https://stackoverflow.com/questions/4310953/invalid-date-in-safari 23 time = time.replace(new RegExp(/-/gm), '/') 24 } 25 } 26 27 if ((typeof time === 'number') && (time.toString().length === 10)) { 28 time = time * 1000 29 } 30 date = new Date(time) 31 } 32 const formatObj = { 33 y: date.getFullYear(), 34 m: date.getMonth() + 1, 35 d: date.getDate(), 36 h: date.getHours(), 37 i: date.getMinutes(), 38 s: date.getSeconds(), 39 a: date.getDay() 40 } 41 const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => { 42 const value = formatObj[key] 43 // Note: getDay() returns 0 on Sunday 44 if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] } 45 return value.toString().padStart(2, '0') 46 }) 47 return time_str 48 } 49 50 /** 51 * @param {number} time 52 * @param {string} option 53 * @returns {string} 54 */ 55 export function formatTime(time, option) { 56 if (('' + time).length === 10) { 57 time = parseInt(time) * 1000 58 } else { 59 time = +time 60 } 61 const d = new Date(time) 62 const now = Date.now() 63 64 const diff = (now - d) / 1000 65 66 if (diff < 30) { 67 return '刚刚' 68 } else if (diff < 3600) { 69 // less 1 hour 70 return Math.ceil(diff / 60) + '分钟前' 71 } else if (diff < 3600 * 24) { 72 return Math.ceil(diff / 3600) + '小时前' 73 } else if (diff < 3600 * 24 * 2) { 74 return '1天前' 75 } 76 if (option) { 77 return parseTime(time, option) 78 } else { 79 return ( 80 d.getMonth() + 81 1 + 82 '月' + 83 d.getDate() + 84 '日' + 85 d.getHours() + 86 '时' + 87 d.getMinutes() + 88 '分' 89 ) 90 } 91 }
const start = new Date()
formatTime(start, '{y}-{m}-{d}', 0)
浙公网安备 33010602011771号