js獲取當前天是一年中的第幾天

解決思路

用當前天的時間戳 - 當前年第一天的時間戳 ,用時間戳差計算出多少天。

代碼

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())

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章