gpt4 book ai didi

java - 计算两个 Java 日期实例之间的差异

转载 作者:bug小助手 更新时间:2023-10-28 01:38:08 33 4
gpt4 key购买 nike

我在 Scala 中使用 Java 的 java.util.Date 类,想比较 Date 对象和当前时间。我知道我可以使用 getTime() 计算增量:

(new java.util.Date()).getTime() - oldDate.getTime()

但是,这只会给我留下一个代表毫秒的 long。有没有更简单、更好的方法来获得时间增量?

最佳答案

简单的差异(没有库)

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

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

TimeUnitjava.util.concurrent.TimeUnit,一个从 nanos 到 days 的标准 Java 枚举。


人类可读的差异(没有库)

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},带有单位已订购。

您只需将该 map 转换为用户友好的字符串。


警告

上面的代码片段计算了两个瞬间之间的简单差异。它可能会在夏令时切换期间引起问题,如 this post 中所述。 .这意味着如果您计算没有时间的日期之间的差异,您可能会丢失日期/小时。

在我看来,日期差异有点主观,尤其是在日子里。你可以:

  • 计算24小时过去的次数:day+1 - day = 1 day = 24h

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

  • 计算day switch的次数,表示day+1 1pm - day 11am = 1 天,即使耗时只有 2 小时(如果有夏令时,则为 1 小时) :p)

如果您对日期差异的定义与第一种情况匹配,我的回答是有效的

使用 JodaTime

如果您使用 JodaTime,您可以通过以下方式获得 2 个即时(由 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 - 计算两个 Java 日期实例之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1555262/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com