如何使用基本java计算两个日期之间的差异

时间:2022-12-13 03:01:10

I just started going to university and basically just started using java and I want to know how to make a code that calculates the days between two dates but without the use of programs that take milliseconds and such things that I have seen in other answers.So this is the code I have created but it doesnt work perfectly it misses one day most of the times or something like that.Please I really need your help

我刚刚开始上大学,基本上刚刚开始使用java,我想知道如何制作一个代码,计算两个日期之间的天数,但不使用花费几毫秒的程序,以及我在其他答案中看到过的东西。所以这是我创建的代码,但它没有完美的工作,大多数时候都会错过一天或类似的事情。请真的需要你的帮助

3 个解决方案

#1


0  

Use a SimpleCalendar or GregorianCalendar classes...

使用SimpleCalendar或GregorianCalendar类......

but basing on what you posted, I'm unsure how to best suggest using those two... i'll draft a simple example shortly.

但基于你发布的内容,我不确定如何最好地建议使用这两个...我将很快起草一个简单的例子。

After some thought I'll just leave this here Difference in days between two dates in Java?

经过一番思考后我会把它留在这里Java中两个日期之间的差异?

#2


0  

Taken from: http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm

摘自:http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm

An approach could be to calculate the number of days from a fixed time for both dates and then just subtract those days. This will give you the difference of days between date 1 and date 2

一种方法可以是计算两个日期的固定时间的天数,然后只减去这些天数。这将为您提供日期1和日期2之间的天数差异

The following method returns the number of days passed since 0 January 0 CE

以下方法返回自1月0日0日以来经过的天数

public int calculateDate( int day, int month, int year) {
  if (month < 3) {
      year--;
      month = month + 12;
  } 
  return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62); 
}

In you code now you should calculate the number of days since 0BC for both dates and then subtract them:

在您的代码中,您应该计算两个日期以来0BC以来的天数,然后减去它们:

public void run() {
 ....

 int dayDifference = calculateDate(day1, month1, year1) - calculateDate(day2, month2, year2);

....
}

#3


0  

tl;dr

java.time.temporal.ChronoUnit.DAYS.between(
    LocalDate.of( 2012 , Month.MARCH , 23 ) ,
    LocalDate.of( 2012 , Month.MAY , 17 ) 
)

55

java.time

The modern approach uses java.time classes that supplant the troublesome old legacy date-time classes.

现代方法使用java.time类来取代麻烦的旧遗留日期时间类。

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate类表示没有时间且没有时区的仅日期值。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,法国巴黎午夜过后几分钟,在魁北克蒙特利尔的“昨天”仍然是新的一天。

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

如果未指定时区,则JVM会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好明确指定您期望/预期的时区作为参数。

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

以洲/地区的格式指定适当的时区名称,例如America / Montreal,Africa / Casablanca或Pacific / Auckland。切勿使用3-4字母缩写,例如EST或IST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

如果要使用JVM的当前默认时区,请求它并作为参数传递。如果省略,则隐式应用JVM的当前默认值。最好是显式的,因为默认情况下可以在运行期间随时由JVM中任何应用程序的任何线程中的任何代码更改。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

或指定日期。您可以将月份设置为一个数字,1月至12月的数字为1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

或者,更好的是,使用预定义的月枚举对象,一年中的每个月一个。提示:在整个代码库中使用这些Month对象而不仅仅是整数,以使代码更加自我记录,确保有效值并提供类型安全性。

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

ChronoUnit.DAYS

To get a count of days between two dates, call on the ChronoUnit enum object DAYS.

要获取两个日期之间的天数,请调用ChronoUnit枚举对象DAYS。

long days = ChronoUnit.DAYS.between( earlierLocalDate , laterLocalDate ) ;

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.

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

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

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

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

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

Where to obtain the java.time classes?

从哪里获取java.time类?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。

    • Java 9 adds some minor features and fixes.
    • Java 9增加了一些小功能和修复。

  • Java SE 8,Java SE 9和更高版本内置。带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小功能和修复。

  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Java SE 6和Java SE 7许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • 更高版本的Android捆绑java.time类的实现。

    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android,ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

  • Android更新版本的Android捆绑java.time类的实现。对于早期的Android,ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

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.

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,如Interval,YearWeek,YearQuarter等。

#1


0  

Use a SimpleCalendar or GregorianCalendar classes...

使用SimpleCalendar或GregorianCalendar类......

but basing on what you posted, I'm unsure how to best suggest using those two... i'll draft a simple example shortly.

但基于你发布的内容,我不确定如何最好地建议使用这两个...我将很快起草一个简单的例子。

After some thought I'll just leave this here Difference in days between two dates in Java?

经过一番思考后我会把它留在这里Java中两个日期之间的差异?

#2


0  

Taken from: http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm

摘自:http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm

An approach could be to calculate the number of days from a fixed time for both dates and then just subtract those days. This will give you the difference of days between date 1 and date 2

一种方法可以是计算两个日期的固定时间的天数,然后只减去这些天数。这将为您提供日期1和日期2之间的天数差异

The following method returns the number of days passed since 0 January 0 CE

以下方法返回自1月0日0日以来经过的天数

public int calculateDate( int day, int month, int year) {
  if (month < 3) {
      year--;
      month = month + 12;
  } 
  return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62); 
}

In you code now you should calculate the number of days since 0BC for both dates and then subtract them:

在您的代码中,您应该计算两个日期以来0BC以来的天数,然后减去它们:

public void run() {
 ....

 int dayDifference = calculateDate(day1, month1, year1) - calculateDate(day2, month2, year2);

....
}

#3


0  

tl;dr

java.time.temporal.ChronoUnit.DAYS.between(
    LocalDate.of( 2012 , Month.MARCH , 23 ) ,
    LocalDate.of( 2012 , Month.MAY , 17 ) 
)

55

java.time

The modern approach uses java.time classes that supplant the troublesome old legacy date-time classes.

现代方法使用java.time类来取代麻烦的旧遗留日期时间类。

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate类表示没有时间且没有时区的仅日期值。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,法国巴黎午夜过后几分钟,在魁北克蒙特利尔的“昨天”仍然是新的一天。

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

如果未指定时区,则JVM会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好明确指定您期望/预期的时区作为参数。

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

以洲/地区的格式指定适当的时区名称,例如America / Montreal,Africa / Casablanca或Pacific / Auckland。切勿使用3-4字母缩写,例如EST或IST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

如果要使用JVM的当前默认时区,请求它并作为参数传递。如果省略,则隐式应用JVM的当前默认值。最好是显式的,因为默认情况下可以在运行期间随时由JVM中任何应用程序的任何线程中的任何代码更改。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

或指定日期。您可以将月份设置为一个数字,1月至12月的数字为1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

或者,更好的是,使用预定义的月枚举对象,一年中的每个月一个。提示:在整个代码库中使用这些Month对象而不仅仅是整数,以使代码更加自我记录,确保有效值并提供类型安全性。

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

ChronoUnit.DAYS

To get a count of days between two dates, call on the ChronoUnit enum object DAYS.

要获取两个日期之间的天数,请调用ChronoUnit枚举对象DAYS。

long days = ChronoUnit.DAYS.between( earlierLocalDate , laterLocalDate ) ;

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.

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

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

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

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

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

Where to obtain the java.time classes?

从哪里获取java.time类?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。

    • Java 9 adds some minor features and fixes.
    • Java 9增加了一些小功能和修复。

  • Java SE 8,Java SE 9和更高版本内置。带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小功能和修复。

  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Java SE 6和Java SE 7许多java.time功能都被反向移植到ThreeTen-Backport中的Java 6和7。

  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • 更高版本的Android捆绑java.time类的实现。

    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android,ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

  • Android更新版本的Android捆绑java.time类的实现。对于早期的Android,ThreeTenABP项目采用ThreeTen-Backport(如上所述)。请参见如何使用ThreeTenABP ....

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.

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。您可以在这里找到一些有用的课程,如Interval,YearWeek,YearQuarter等。