是否有任何本机 Java 类中的方法来计算特定年份有多少天/将有多少天?例如,是闰年(366 天)还是平年(365 天)?
还是我需要自己写?
我正在计算两个日期之间的天数,例如,距离我的生日还有多少天。我想考虑到闰年的 2 月 29 日。除了 29 号以外,我都完成了。
另一种方法是向Calendar
班级询问给定年份的实际最长天数:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int numOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
System.out.println(numOfDays);
这将返回 366 表示双分年份,365 表示正常年份。
请注意,我使用getActualMaximum
了而不是getMaximum
,它总是返回 366。
标准类GregorianCalendar
有一个isLeapyear()
方法。如果你得到的只是一个年份数字(比如),那么使用这个2008
构造函数构造一个日期,然后检查这个方法。isLeapYear()
一年中的天数:
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;
For DateTime calculations I highly recommend using the JodaTime library. For what you need, in particular, it would be a one liner:
Days.daysBetween(date1, date2).getDays();
I hope this helps.
使用 Joda 和这个特定示例可能最好地解决您的确切用例。
您可以查看Wikipedia 页面以获得一些非常好的伪代码:
if year modulo 400 is 0
then is_leap_year
else if year modulo 100 is 0
then not_leap_year
else if year modulo 4 is 0
then is_leap_year
else
not_leap_year
我相信您可以弄清楚如何在 Java 中实现该逻辑。:-)
您可以使用TimeUnit类。对于您的特定需求,这应该这样做:
public static int daysBetween(Date a, Date b) {
final long dMs = a.getTime() - b.getTime();
return TimeUnit.DAYS.convert(dMs, TimeUnit.MILLISECONDS);
}
老实说,我看不出闰年在这个计算中起到什么作用。也许我错过了你问题的某些方面?
编辑:愚蠢的我,闰年魔法发生在Date.getTime()
. 无论如何,您不必以这种方式处理它。