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
Constraints:
date.length == 10
date[4] == date[7] == '-'
, and all otherdate[i]
's are digitsdate
represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019.
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = (int(e) for e in date.split('-'))
d = 29 if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) else 28
days = [31, d, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return sum(days[: month - 1]) + day
class Solution {
public int dayOfYear(String date) {
int year = Integer.parseInt(date.substring(0, 4));
int month = Integer.parseInt(date.substring(5, 7));
int day = Integer.parseInt(date.substring(8));
int d = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) ? 29 : 28;
int[] days = new int[] {31, d, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int ans = day;
for (int i = 0; i < month - 1; ++i) {
ans += days[i];
}
return ans;
}
}
class Solution {
public:
int dayOfYear(string date) {
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 7));
int day = stoi(date.substr(8));
int d = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0) ? 29 : 28;
int days[] = {31, d, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int ans = day;
for (int i = 0; i < month - 1; ++i) ans += days[i];
return ans;
}
};
func dayOfYear(date string) int {
year, _ := strconv.Atoi(date[:4])
month, _ := strconv.Atoi(date[5:7])
day, _ := strconv.Atoi(date[8:])
days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
if year%400 == 0 || (year%4 == 0 && year%100 != 0) {
days[1]++
}
ans := day
for i := 0; i < month-1; i++ {
ans += days[i]
}
return ans
}
/**
* @param {string} date
* @return {number}
*/
var dayOfYear = function (date) {
const year = +date.slice(0, 4);
const month = +date.slice(5, 7);
const day = +date.slice(8);
const d =
year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0) ? 29 : 28;
const days = [31, d, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let ans = day;
for (let i = 0; i < month - 1; ++i) {
ans += days[i];
}
return ans;
};