JS獲取當前時間的前一個小時及格式化時間
阿新 • • 發佈:2018-11-02
一、當前時間的前一個小時
var frontOneHour = new Date(new Date().getTime() - 1 * 60 * 60 * 1000);
console.log(new Date(new Date().getTime() - 1 * 60 * 60 * 1000), new Date()) // 前一個小時 當前時間
console.log(frontOneHour)
二、格式化時間
// js
function frontOneHour (fmt) {
var currentTime = new Date(new Date().getTime())
console.log(currentTime) // Wed Jun 20 2018 16:12:12 GMT+0800 (中國標準時間)
var o = {
'M+': currentTime.getMonth() + 1, // 月份
'd+': currentTime.getDate(), // 日
'h+': currentTime.getHours(), // 小時
'm+': currentTime.getMinutes(), // 分
's+': currentTime.getSeconds(), // 秒
'q+': Math.floor((currentTime.getMonth() + 3) / 3), // 季度
'S': currentTime.getMilliseconds() // 毫秒
}
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (currentTime.getFullYear() + '').substr(4 - RegExp.$1.length))
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
}
return fmt
}
// 呼叫
frontOneHour('yyyy-MM-dd hh:mm:ss') // "2018-06-20 16:11:59"
frontOneHour('yyyy-MM-dd') // "2018-06-20"
frontOneHour('yyyyMMDD') // "201806DD"