在java中如何计算两个日期的间隔?

在java中如何计算两个日期的间隔?

回答:

简单差异(无lib)

/**

* Get a diff between two dates

* @param date1 the oldest date

* @param date2 the newest date

* @param timeUnit the unit in which you want the diff

* @return the diff value, in the provided unit

*/

public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {

long diffInMillies = date2.getTime() - date1.getTime();

return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);

}

然后你可以致电:

getDateDiff(date1,date2,TimeUnit.MINUTES);

以分钟为单位获取两个日期的差异。

TimeUnit是java.util.concurrent.TimeUnit,一个标准的Java枚举,范围从nanos到数天。

可读的差异(无lib)

public static Map<TimeUnit,Long> computeDiff(Date date1, Date date2) {

long diffInMillies = date2.getTime() - date1.getTime();

//create the list

List<TimeUnit> units = new ArrayList<TimeUnit>(EnumSet.allOf(TimeUnit.class));

Collections.reverse(units);

//create the result map of TimeUnit and difference

Map<TimeUnit,Long> result = new LinkedHashMap<TimeUnit,Long>();

long milliesRest = diffInMillies;

for ( TimeUnit unit : units ) {

//calculate difference in millisecond

long diff = unit.convert(milliesRest,TimeUnit.MILLISECONDS);

long diffInMilliesForUnit = unit.toMillis(diff);

milliesRest = milliesRest - diffInMilliesForUnit;

//put the result in the map

result.put(unit,diff);

}

return result;

}

http://ideone.com/5dXeu6

输出类似于Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0},带有单位排序。

你只需要将该映射转换为用户友好的字符串即可。

警告

上面的代码片段计算了两个瞬间之间的简单差异。它可以在夏令开关过程中导致问题,就像在解释这个职位。这意味着,如果你没有时间计算日期之间的差异,则可能会缺少日期/小时。

我认为日期差异是主观的,尤其是在几天内。你可以:

  • 计算24小时经过的时间:天+1-天= 1天= 24小时

  • 计算经过的时间,注意夏令时:day + 1-day = 1 = 24h(但使用午夜时间和夏令时可能是0天和23h)

  • 计算的数量day switches,这意味着day + 1 1pm-day 11am = 1 day,即使经过的时间仅为2h(如果有夏令时,则为1h:p)

如果你对日期的日期差异定义与第一种情况相符,我的答案是有效的

与JodaTime

如果你使用的是JodaTime,则可以使用以下两个日期(以Millies为后盾的ReadableInstant)获取差异:

Interval interval = new Interval(oldInstant, new Instant());

但是你还可以获取本地日期/时间的差异:

// returns 4 because of the leap year of 366 days

new Period(LocalDate.now(), LocalDate.now().plusDays(365*5), PeriodType.years()).getYears()

// this time it returns 5

new Period(LocalDate.now(), LocalDate.now().plusDays(365*5+1), PeriodType.years()).getYears()

// And you can also use these static methods

Years.yearsBetween(LocalDate.now(), LocalDate.now().plusDays(365*5)).getYears()

以上是 在java中如何计算两个日期的间隔? 的全部内容, 来源链接: utcz.com/qa/432054.html

回到顶部