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 computeDiff(Date date1, Date date2) {

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

//create the list

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

Collections.reverse(units);

//create the result map of TimeUnit and difference

Map result = new LinkedHashMap();

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;

}

输出类似于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()

2020-01-08

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值