简体   繁体   English

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

[英]how to calculate difference between two dates using basic java

我刚开始上大学,基本上就开始使用Java,我想知道如何制作一个代码来计算两个日期之间的天数,但不使用花费毫秒的程序以及我在其他答案中已经看到的东西。这是我创建的代码,但无法正常运行,大多数情况下会错过一天或类似的时间。请我真的需要您的帮助

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中两个日期之间的天数差异?

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 下面的方法返回自0 January 0 CE以来经过的天数

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

....
}

tl;dr tl; dr

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

55 55

java.time 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. 如果未指定时区,则JVM隐式应用其当前的默认时区。 That default may change at any moment, so your results may vary. 该默认值可能随时更改,因此您的结果可能会有所不同。 Better to specify your desired/expected time zone explicitly as an argument. 最好将您的期望/期望时区明确指定为参数。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland . continent/region的格式指定正确的时区名称 ,例如America/MontrealAfrica/CasablancaPacific/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(!). 切勿使用ESTIST等3-4个字母的缩写,因为它们不是真实的时区,不是标准化的,甚至不是唯一的(!)。

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. 如果要使用JVM的当前默认时区,请提出要求并作为参数传递。 If omitted, the JVM's current default is applied implicitly. 如果省略,则隐式应用JVM的当前默认值。 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中任何应用程序的任何线程中的任何代码更改。

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。

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. 或者,最好使用预定义的Month枚举对象,一年中的每个月使用一个。 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 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

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 . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM