解決思路
用當前天的時間戳 - 當前年第一天的時間戳 ,用時間戳差計算出多少天。
代碼
Date.prototype.getDayYear = function(){
const year = this.getFullYear();
const month = this.getMonth();
const date = this.getDate();
//當前年第一天0時0分0秒的時間戳
const firstTimestamp = new Date(`${year}-1-1 00:00:00`);
// 當前天的時間戳,
const currentTimestamp = new Date(`${year}-${month}-${date} 23:59:59`).getTime();
// 時間差 = 當前天時間戳 - 當前年第一天時間戳
const hasTimestamp = currentTimestamp - firstTimestamp;
// 一天的時間戳
const time = 24 * 60 * 60 * 1000;
// 計算有多少天
const hasDays = Math.ceil(hasTimestamp/time);
return hasDays;
}
console.log(new Date(2020,1,2).getDayYear())
console.log(new Date(2020,2,2).getDayYear())