java计算日历天数的方法,Java计算一年中的天数,或两个日期之间的天数

这篇博客介绍了如何利用Java 8的LocalDate类来计算一年中的天数,特别考虑了闰年的情况。通过LocalDate的lengthOfYear()方法可以获取当年的总天数,同时展示了计算生日日期与当前日期之间天数的方法,确保在闰年2月29日的处理上是准确的。
摘要由CSDN通过智能技术生成

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)?

Or do I need to write it myself?

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.

解决方案

since JAVA 8

Days in a year:

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

return d.lengthOfYear(); // 366

Days to my birthday:

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值