给你一个字符串 date
,按 YYYY-MM-DD
格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
示例 1:
输入:date = "2019-01-09" 输出:9 解释:给定日期是2019年的第九天。
示例 2:
输入:date = "2019-02-10" 输出:41
提示:
date.length == 10
date[4] == date[7] == '-'
,其他的date[i]
都是数字date
表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
闰年 2 月有 29 天,平年 2 月有 28 天。
闰年的判断规则:year % 100 == 0 || (year % 4 == 0 && year % 100 != 0)
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;
};