Java 计算一年中的天数或两个日期之间的天数

发布于 2024-10-14 05:23:15 字数 224 浏览 1 评论 0原文

任何本机 Java 类中是否有一种方法可以计算特定年份中过去/将有多少天?例如,这是闰年(366天)还是平年(365天)?

还是需要我自己写?

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

烟花易冷人易散 2024-10-21 05:23:15

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

Another way to do it is to ask the Calendar class for the actual maximum days in a given year:

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());

int numOfDays = cal.getActualMaximum(Calendar.DAY_OF_YEAR);
System.out.println(numOfDays);

This will return 366 for a bisestile year, 365 for a normal one.

Note, I used getActualMaximum instead of getMaximum, which will always returns 366.

棒棒糖 2024-10-21 05:23:15

tl;dr

Year.of( 2015 ).length()

…和…

Year.isLeap( 2015 )

java.time.Year

在 Java 8 及更高版本中,我们有 java.time 包。 (教程)

长度

Year 类代表单个年份值。你可以询问它的长度。

int daysInYear = Year.of( 2015 ).length();

isLeap

您还可以询问某一年是否是闰年。

Boolean isLeapYear = Year.isLeap( 2015 );

举个例子,使用Java的三元运算符获取一年中的天数,例如:

minVal = (a < b) ? a:b;

在我们的例子中,我们需要一年中的天数。非闰年为 365,闰年为 366。

int daysInYear = ( Year.isLeap( 2015 ) ) ? 366 : 365 ;

年份

您可以获得日期的年份数字。该数字从 1 到 365,闰年为 366。

int dayOfYear = LocalDate.now( ZoneId.of( "America/Montreal" ).getDayOfYear() ;

换个方向,获取一年中某一天的日期。

Year.now( ZoneId.of( "America/Montreal" ) ).atDay( 159 ) ;

在处理单个年份时,您可以通过比较这些年份数字来确定经过的天数。但还有一个更简单的方法;请继续阅读。

已用天数

使用 ChronoUnit 枚举来计算经过的天数。

LocalDate start = LocalDate.of( 2017 , 2 , 23 ) ;
LocalDate stop = LocalDate.of( 2017 , 3 , 11 ) ;
int daysBetween = ChronoUnit.DAYS.between( start , stop );

自动处理闰年


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历,& SimpleDateFormat

Joda-Time 项目,现位于 维护模式,建议迁移到 java.time 类。

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

从哪里获取 java.time 类?

ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是 java.time 未来可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 IntervalYearWeekYearQuarter,以及更多

tl;dr

Year.of( 2015 ).length()

…and…

Year.isLeap( 2015 )

java.time.Year

In Java 8 and later we have the java.time package. (Tutorial)

length

The Year class represents a single year value. You can interrogate its length.

int daysInYear = Year.of( 2015 ).length();

isLeap

You can also ask if a year is a Leap year or not.

Boolean isLeapYear = Year.isLeap( 2015 );

As an example, get the number of days in year using Java’s ternary operator, such as:

minVal = (a < b) ? a : b;

In our case, we want number of days of year. That is 365 for non-Leap years, and 366 for Leap year.

int daysInYear = ( Year.isLeap( 2015 ) ) ? 366 : 365 ;

Day-of-year

You can get the day-of-year number of a date. That number runs from 1 to 365, or 366 in a leap year.

int dayOfYear = LocalDate.now( ZoneId.of( "America/Montreal" ).getDayOfYear() ;

Going the other direction, get a date for a day-of-year.

Year.now( ZoneId.of( "America/Montreal" ) ).atDay( 159 ) ;

You could determine elapsed days by comparing these day-of-year numbers when dealing with a single year. But there is an easier way; read on.

Elapsed days

Use the ChronoUnit enum to calculate elapsed days.

LocalDate start = LocalDate.of( 2017 , 2 , 23 ) ;
LocalDate stop = LocalDate.of( 2017 , 3 , 11 ) ;
int daysBetween = ChronoUnit.DAYS.between( start , stop );

Automatically handles Leap Year.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

左岸枫 2024-10-21 05:23:15

GregorianCalendar 标准类有一个 isLeapyear() 方法。如果您只有年份数字(例如 2008),则使用 this 构造函数,然后检查 isLeapYear()之后的方法。

The GregorianCalendar standar class has an isLeapyear() method. If all you've got is a year number (say, 2008), then construct a date using this constructor, and then check the isLeapYear() method afterwards.

温柔女人霸气范 2024-10-21 05:23:15

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;

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;
长途伴 2024-10-21 05:23:15

对于日期时间计算,我强烈建议使用 JodaTime 库。对于您所需要的,特别是,这将是一个衬垫:

Days.daysBetween(date1, date2).getDays();

我希望这会有所帮助。

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.

一枫情书 2024-10-21 05:23:15

您可以查看维基百科页面以获得一些非常好的伪代码:

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 中实现该逻辑。 :-)

You can look at the Wikipedia page for some very nice pseudocode:

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

I'm sure you can figure out how to implement that logic in Java. :-)

薄凉少年不暖心 2024-10-21 05:23:15

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

You exact use case might be best solved with Joda and this specific example.

情定在深秋 2024-10-21 05:23:15

您可以使用 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()中。无论如何,你不必这样处理。

You can use the TimeUnit class. For your specific needs this should do:

public static int daysBetween(Date a, Date b) {
    final long dMs = a.getTime() - b.getTime();
    return TimeUnit.DAYS.convert(dMs, TimeUnit.MILLISECONDS);
}

Honestly, I don't see where leap years play any role in this calculation, though. Maybe I missed some aspect of your question?

Edit: Stupid me, the leap years magic happens in the Date.getTime(). Anyway, you don't have to deal with it this way.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文