Suppose, we have a date in the format “YYYY-MM-DD”. We have to return the day number of the year. So if the date is “2019-02-10”, then this is 41st day of the year.
To solve this, we will follow these steps −
- Suppose D is an array of day count like [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- Convert the date into list of year, month and day
- if the year is leap year then set date D[2] = 29
- Add up the day count up to the month mm – 1. and day count after that.
Example
Let us see the following implementation to get better understanding −
class Solution(object): def dayOfYear(self, date): days = [0,31,28,31,30,31,30,31,31,30,31,30,31] d = list(map(int,date.split("-"))) if d[0] % 400 == 0: days[2]+=1 elif d[0]%4 == 0 and d[0]%100!=0: days[2]+=1 for i in range(1,len(days)): days[i]+=days[i-1] return days[d[1]-1]+d[2] ob1 = Solution() print(ob1.dayOfYear("2019-02-10"))
Input
"2019-02-10"
Output
41