Java计算一年中的天数,或两个日期之间的天数 [英] Java calculate days in year, or between two dates

查看:732
本文介绍了Java计算一年中的天数,或两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何本机Java类中是否都存在一种方法来计算特定年份中的多少天/将要多少天?就像是 Le年(366天)还是正常年份(365天)?

Is there a method in any native Java class to calculate how many days were/will be in a specific year? As in, was it a Leap year (366 days) or a normal year (365 days)?

还是我需要自己写?

我正在计算两个日期之间的天数,例如,到我生日还剩多少天.我要考虑到year年2月29日.除了29号,我都做完了.

I'm calculating the number of days between two dates, for example, how many days left until my birthday. I want to take into account the February 29 of Leap year. I have it all done except that 29th.

推荐答案

JAVA 8

一年中的天数:

since JAVA 8

Days in a year:

LocalDate d = LocalDate.parse("2020-12-31");                   // import java.time.LocalDate;
return d.lengthOfYear();                                       // 366

我生日的天数:

LocalDate birth = LocalDate.parse("2000-02-29");
LocalDate today = LocalDate.now();                             // or pass a timezone as the parameter

LocalDate thisYearBirthday = birth.withYear(today.getYear());  // it gives Feb 28 if the birth was on Feb 29, but the year is not leap.
LocalDate nextBirthday = today.isAfter(thisYearBirthday)
    ? birth.withYear(today.getYear() + 1)
    : thisYearBirthday;

return DAYS.between(today, nextBirthday);                      // import static java.time.temporal.ChronoUnit.DAYS;

这篇关于Java计算一年中的天数,或两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆