1154. 一年中的第几天 【简单】

给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。请你计算并返回该日期是当年的第几天。

通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。

示例 1:

输入:date = “2019-01-09”
输出:9
示例 2:

输入:date = “2019-02-10”
输出:41
示例 3:

输入:date = “2003-03-01”
输出:60
示例 4:

输入:date = “2004-03-01”
输出:61
 

提示:

date.length == 10
date[4] == date[7] == ‘-‘,其他的 date[i] 都是数字
date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/day-of-the-year
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解一

使用工具类解析日期和获取天数,效率最低

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

class Solution {
    public int dayOfYear(String date) {
            try {
                return LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd")).getDayOfYear();
            } catch (DateTimeParseException pe1) {
            }
        return -1;
    }
}

题解二

手动解析日期,使用工具类获取第几天,速度大幅提示,占用内存稍好于第一种方法。

    public int dayOfYear(String date) {
        int year = Integer.parseInt(date.substring(0, 4)),
                month = Integer.parseInt(date.substring(5, 7)),
                day = Integer.parseInt(date.substring(8, 10));
        return LocalDate.of(year, month, day).getDayOfYear();
    }

题解三

全部手动计算,效率最高与官方题解大致相同。

public int dayOfYear(String date) {
            int year = Integer.parseInt(date.substring(0,4)), month = Integer.parseInt(date.substring(5,7)), day = Integer.parseInt(date.substring(8,10)), days = 0;
            for(int i=1;i<month;i++){
                if(i == 2){
                    days += (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
                }else if(i<8){
                    days += (i%2==1) ? 31 : 30;
                }else {
                    days += (i%2==0) ? 31 : 30;
                }
            }
        return days + 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[] amount = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            ++amount[1];
        }

        int ans = 0;
        for (int i = 0; i < month - 1; ++i) {
            ans += amount[i];
        }
        return ans + day;
    }
}

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/day-of-the-year/solution/yi-nian-zhong-de-di-ji-tian-by-leetcode-2i0gr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

知识点

闰年的判定方法为:年份 是 400 的倍数,或者是 4 的倍数且不是 100 的倍数。

普通闰年:公历年份是4的倍数,且不是100的倍数的,为闰年(如2004年、2020年等就是闰年)。

世纪闰年:公历年份是整百数的,必须是400的倍数才是闰年(如1900年不是闰年,2000年是闰年)。