23

是否有任何本机 Java 类中的方法来计算特定年份有多少天/将有多少天?例如,是闰年(366 天)还是平年(365 天)?

还是我需要自己写?

我正在计算两个日期之间的天数,例如,距离我的生日还有多少天。我想考虑到闰年的 2 月 29 日。除了 29 号以外,我都完成了。

4

9 回答 9

50

另一种方法是向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。

于 2012-09-17T13:27:48.110 回答
23
于 2015-09-01T02:08:53.280 回答
15

标准类GregorianCalendar有一个isLeapyear()方法。如果你得到的只是一个年份数字(比如),那么使用这个2008构造函数构造一个日期,然后检查这个方法。isLeapYear()

于 2011-01-24T21:47:18.057 回答
7

JAVA 8开始

一年中的天数:

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;
于 2020-01-13T00:21:46.607 回答
6

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.

于 2011-01-24T22:08:49.000 回答
5

GregorianCalendar.isLeapYear(int year)

于 2011-01-24T21:48:01.290 回答
3

使用 Joda 和这个特定示例可能最好地解决您的确切用例。

于 2011-01-24T21:54:23.383 回答
3

您可以查看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 中实现该逻辑。:-)

于 2011-01-24T21:46:46.653 回答
1

您可以使用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(). 无论如何,您不必以这种方式处理它。

于 2011-01-24T21:56:01.083 回答