Date 常用方法
Date對(duì)象實(shí)例
var myDate = new Date(); // new Date() 返回一個(gè)Date對(duì)象實(shí)例
- 不加參數(shù)的話芹敌,實(shí)例代表的是當(dāng)前時(shí)間
- 前面加 “+”號(hào)可以將其轉(zhuǎn)化成時(shí)間毫秒數(shù)
獲取當(dāng)前時(shí)間距離時(shí)間零點(diǎn)的毫秒數(shù)
Date.now()
獲取時(shí)間毫秒數(shù)
myDate.getTime();
獲取年份
myDate.getFullYear(); // 2018
注意 myDate.getYear()
返回的是距離1900年的年數(shù)
獲取月份(0-11搭盾, 0代表1月)
myDate.getMonth();
獲取當(dāng)前日期是幾號(hào)(1-31)
myDate.getDate();
獲取當(dāng)前是星期幾斤吐,周日為0 ....
myDate.getDay()
formatDate 函數(shù)
function(str) {
if (!str) return ''
let targetTime = +new Date(str);
let curTime = Date.now();
let t = (curTime - targetTime) / 1000; // 時(shí)間差,單位: 秒
// 或者 let t = (new Date().getTime() -new Date(str).getTime()) /1000
if (t < 0) {
return ''
} else if (t < 30) {
return '剛剛' // 30秒內(nèi)
} else if (t < 60 * 60) { // 1 小時(shí)內(nèi)
return parseInt(t / 60) + '分鐘前'
} else if (t < 60 * 60 * 24) { // 1 天內(nèi)
return parseInt(t / (60 * 60)) + '小時(shí)前'
} else if (t < 60 * 60 * 24 * 31) { // 一個(gè)月內(nèi)
return parseInt(t / (60 * 60 * 24)) + '天前'
} else if (t < 60 * 60 * 24 * 30 * 12) { // 一年內(nèi)
return parseInt(t / (60 * 60 * 24 * 30)) + '個(gè)月前'
} else { // 一年以上
return parseInt(t / (60 * 60 * 24 * 365)) + '年前'
}