# 1154. 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:

• `date.length == 10`
• `date[4] == date[7] == '-'`, and all other `date[i]`‘s are digits
• `date` represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.

``````class Solution {
public:
int dayOfYear(string date) {
vector<int> monthDays{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int res = 0, year = stoi(date.substr(0, 4)), month = stoi(date.substr(5, 2)), day = stoi(date.substr(8, 2));
for (int i = 0; i < month - 1; ++i) {
res += monthDays[i];
}
if (month > 2 && (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))) {
++res;
}
return res + day;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1154

https://leetcode.com/problems/day-of-the-year/

https://leetcode.com/problems/day-of-the-year/discuss/355916/C%2B%2B-Number-of-Days-in-a-Month

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation