因爲項目有多個後端人員,不免會出現返回時間樣式不統一現象,但前端顯示又要統一,先上代碼前端
// params => "2019-04-02 17:11:55" OR 1554257391000 (毫秒) 只需調用此函數 function formatRecentTime(params) { var date = '' if (isNaN(params)) { // 判斷是不是時間戳 date = params.toString() } else { date = timeFormat(params) } var year = date.substring(0, 4) var month = date.substring(5, 7) var day = date.substring(8, 10) var hour = date.substring(11, 13) var minute = date.substring(14, 16) var seconds = date.substring(17, 19) var orignDate = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + seconds var yesterday = GetDateStr(-1)// 昨天 var yesterdayStr = yesterday.split('-') yesterdayStr[1] = yesterdayStr[1].length === 1 ? '0' + yesterdayStr[1] : yesterdayStr[1] yesterdayStr[2] = yesterdayStr[2].length === 1 ? '0' + yesterdayStr[2] : yesterdayStr[2] var today = GetDateStr(0)// 今天 var todayStr = today.split('-') todayStr[1] = todayStr[1].length === 1 ? '0' + todayStr[1] : todayStr[1] todayStr[2] = todayStr[2].length === 1 ? '0' + todayStr[2] : todayStr[2] var tomorrow = GetDateStr(1)// 明天 var tomorrowStr = tomorrow.split('-') tomorrowStr[1] = tomorrowStr[1].length === 1 ? '0' + tomorrowStr[1] : tomorrowStr[1] tomorrowStr[2] = tomorrowStr[2].length === 1 ? '0' + tomorrowStr[2] : tomorrowStr[2] var afterTomorrow = GetDateStr(2)// 後天 var afterTomorrowStr = afterTomorrow.split('-') afterTomorrowStr[1] = afterTomorrowStr[1].length === 1 ? '0' + afterTomorrowStr[1] : afterTomorrowStr[1] afterTomorrowStr[2] = afterTomorrowStr[2].length === 1 ? '0' + afterTomorrowStr[2] : afterTomorrowStr[2] if (year === yesterdayStr[0] && month === yesterdayStr[1] && day === yesterdayStr[2]) { return '昨天' + ' ' + hour + ':' + minute } else if (year === todayStr[0] && month === todayStr[1] && day === todayStr[2]) { return '今天' + ' ' + hour + ':' + minute } else if (year === tomorrowStr[0] && month === tomorrowStr[1] && day === tomorrowStr[2]) { return '明天' + ' ' + hour + ':' + minute } else if (year === afterTomorrowStr[0] && month === afterTomorrowStr[1] && day === afterTomorrowStr[2]) { return '後天' + ' ' + hour + ':' + minute } else { return orignDate } } // 時間戳轉化成時間格式 function timeFormat(timestamp) { var time = new Date(timestamp) var year = time.getFullYear() var month = time.getMonth() + 1 var date = time.getDate() var hours = time.getHours() var minutes = time.getMinutes() var seconds = time.getSeconds() return year + '-' + add0(month) + '-' + add0(date) + ' ' + add0(hours) + ':' + add0(minutes) + ':' + add0(seconds) } // 保證不出現個位數狀況 function add0(m) { return m < 10 ? '0' + m : m } function GetDateStr(AddDayCount) { var dd = new Date() dd.setDate(dd.getDate() + AddDayCount) var y = dd.getFullYear() var m = dd.getMonth() + 1 var d = dd.getDate() return y + '-' + m + '-' + d }