Create a function getDays, pass a date, and return the day of the year that date is.

Create a function getDays, pass a date, and return the day of the year that date is.

insert image description here

Method 1. Add all the days and dates of the month before a time period

//创建一个函数
			function getDays(year,month,date){
    
    
			//保存传递过来的值
				var n=new Date(year,month-1,date)
			//判断二月的天数
				var tow= year%4===0 && year%100 !==0 || year%400===0 ? 29:28
			//创建数组遍历获取月份天数
				var arr=[31,tow,31,30,31,30,31,31,30,31,30,31]
				for(var i=0,sum=0; i<month-1;i++){
    
    
			//将月份的天数和加起来
					sum=sum+arr[i]
				}
			//返回月份的天数和日期的天数
				return sum+date
			}
			console.log(getDays(2022,9,6)) 

Method 2: Subtract the initial time of the year from the passed time to get the number of days

function getDays(year,month,date){
    
    
				//保存当前传入的日期时间
				var d1=new Date(year,month-1,date)
				//创建一年中的初始时间
				var d2=new Date(year,0,0)
				//时间相减,获取时间毫秒
				var d3=d1.getTime()-d2.getTime()
				//返回相减的时间然后对时间进行乘除操作获取天数(除以1000变成秒,除以60变成分钟,除以60变成小时,除以24,变成天数)
				return d3/(24*60*60*1000)			
			}
			console.log(getDays(2022,9,6))

Guess you like

Origin blog.csdn.net/m0_65792710/article/details/126820241