Day of the Year

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

 

Example 1:

Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.

Example 2:

Input: date = "2019-02-10"
Output: 41

Example 3:

Input: date = "2003-03-01"
Output: 60

Example 4:

Input: date = "2004-03-01"
Output: 61

 

Constraints:


Solution:

class Solution {
    public int dayOfYear(String date) {
        Map<Integer, Integer> monthToDays = new HashMap();
        monthToDays.put(1, 31);
        monthToDays.put(2, 28);
        monthToDays.put(3, 31);
        monthToDays.put(4, 30);
        monthToDays.put(5, 31);
        monthToDays.put(6, 30);
        monthToDays.put(7, 31);
        monthToDays.put(8, 31);
        monthToDays.put(9, 30);
        monthToDays.put(10, 31);
        monthToDays.put(11, 30);
        monthToDays.put(12, 31);
        String[] arr = date.split("-");
        int year = Integer.parseInt(arr[0]);
        int month = Integer.parseInt(arr[1]);
        int day = Integer.parseInt(arr[2]);
        if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
            monthToDays.put(2, 29);
        }
        int d = 0;
        for (int i = 1; i < month; i ++) {
            d += monthToDays.get(i);
        }
        d += day;
        return d;
    }
}