JavaScript (detailed) provides year-month-day, how many days is the output in this year?

Input year-month-day, how many days is the output?


  • Ideas:
  • If you enter 2018-11-11, how many days is the calculation in this year?
  •      Use the number of days in the previous 10 months and add 11, the number of days in the 11th month.

 
  •    question:

  •    This involves the number of days in February in a leap year.
  •       In a normal year, February has 28 days, and in a leap year, it has 29 days.

    -------------
    Code logic:
  1. If the input is January, you can directly output the number of days, which is the number of days in the year.
  2. We first give the number of days in February 28 days, if it is a leap year, let it add one more day.
  3. If it is January and February, it doesn't matter whether it is a leap year or a normal year, because it will give the number of days; so from the conditions of March, to judge whether it is a leap year or a normal year, if it is a leap year, add 1 day to the total number of days.

<script>
    
    /* Enter the year, month and day, and judge the day of the year*/
    var aryDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    function isLeapYear(year)
    {
        if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
        {
            return true; // is a leap year
        }
        else
        {
        	return false; // is a normal year
        }
	}

    function getDate (year, month, days)
    {
        if(month == 1) //If the input is January, directly output the number of days
        {
        	return days;
        }

        for(var i = 0; i < month - 1; i++) //If the input is not January, use the sum of the previous (month - 1) month and add the number of days
        {
            days += aryDays[i];
        }

		if(isLeapYear(year) && month > 2) //Determine whether it is a normal year or a leap year, and the number of days in February is different
		{
			days++;
		}

		return days;
	}

	console.log(getDate(2000, 3, 2));

</script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778136&siteId=291194637