Day of the Year
Let’s write a function to calculate the day number of the given year for a date formatted as “YYYY-MM-DD”.
Here’s a step-by-step guide:
- Split the date string into the year, month, and day components.
- Create a list containing the number of days in each month. For a leap year, adjust the number of days in February to 29.
- Calculate the total days by summing the days in the previous months and adding the current day.
- Return the total number of days.
A year is a leap year if it’s divisible by 400, or divisible by 4 and not divisible by 100.
Here’s the code:
|
|
Explanation:
- First, we split the date into year, month, and day.
- We define the number of days in each month, considering February as 28 days initially.
- If the year is a leap year, we update February’s days to 29.
- Finally, we calculate the total days by summing up the days of the previous months and adding the current day, and return this value.