1.把時間戳或帶格式的日期轉換成標准格式
new Date()//轉換成標准日期格式
如:2013-11-11,先用new Date('2013-11-11')轉換成標准格式:Mon Nov 11 2013 08:00:00 GMT+0800 (中國標准時間)
如:1398250549490,先用new Date(1535760000000)轉換成標准格式:Sat Sep 01 2018 08:00:00 GMT+0800 (中國標准時間)
將時間戳轉換為指定的格式的方法:比如轉換成 年月日時分秒 這種格式:yyyy-MM-dd hh:mm:ss 或者 yyyy-MM-dd。
function DateFormat (date, fmt) {//要轉換的date日期,fmt返回的格式 let o = { 'M+': date.getMonth() + 1, // 月份 'd+': date.getDate(), // 日 'h+': date.getHours(), // 小時 'm+': date.getMinutes(), // 分 's+': date.getSeconds(), // 秒 'q+': Math.floor((date.getMonth() + 3) / 3), // 季度 'S': date.getMilliseconds(), // 毫秒 } if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) for (let 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 }
引用方法
DateFormat(1535760000000, 'yyyy-MM-dd')//將前面的數字日期的格式轉換成yyyy-MM-dd樣式
DateFormat(1535760000000, 'yyyy-MM-dd hh:mm:ss')//將前面的數字日期的格式轉換成yyyy-MM-dd hh:mm:ss樣式2
2.把日期轉換成時間戳,獲取精准的時間戳
new Date(time).getTime()
如:
console.log(new Date('2013-11-11 13:34:04').getTime())
3.判斷日期是否為昨天
// 判斷日期是否為昨天 function isYestday (theDate) { let date = (new Date())// 當前時間 let today = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() // 今天凌晨 let yestday = new Date(today - 24 * 3600 * 1000).getTime() return theDate.getTime() < today && yestday <= theDate.getTime()
}
//調用
let time = new Date('2013-11-11')
isYestday(time) //false time為標准時間格式 Mon Nov 11 2013 08:00:00 GMT+0800 (中國標准時間)
4.js獲取今天0點的時間戳和23.59分的時間戳
let startTime1 = new Date(new Date(new Date().toLocaleDateString()).getTime()); // 當天0點 let endTime1 = new Date(new Date(new Date().toLocaleDateString()).getTime() +24 * 60 * 60 * 1000 -1);// 當天23:59