获取两个java.util.Date的平均值 [英] Get Average of two java.util.Date

查看:112
本文介绍了获取两个java.util.Date的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java.util.Date对象数组。我想找到平均值。

I have an array of java.util.Date objects. I am trying to find the average.

例如,如果我在上午7:40和上午7:50有2个日期对象。我应该得到一个平均日期对象上午7:45。

For example, if I have 2 date objects with 7:40AM and 7:50AM. I should get an average date object of 7:45AM.

我想的方法效率低下:


  1. 循环播放所有日期

  2. 查找0000与时间之间的差异

  3. 将时间差异添加到总计
  4. li>
  5. 除以总计数

  6. 将该时间转换为日期对象

  1. for loop through all dates
  2. find difference between 0000 and time
  3. add that time diff to a total
  4. divide that by the total count
  5. convert that time to a date object

这是否有更简单的功能?

Is there an easier function to do this?

推荐答案

从根本上说,你可以加上millis因为Unix纪元所有日期对象并找到那些的平均值。现在棘手的一点是避免溢出。选项包括:

Well fundamentally you can just add up the "millis since the Unix epoch" of all the Date objects and find the average of those. Now the tricky bit is avoiding overflow. Options are:


  1. 除以某些已知数量(例如1000)以避免溢出;这会降低已知金额的精确度(在这种情况下为第二次),但如果您的项目数超过1000则会失败

  2. 将每个毫秒值除以您平均的日期数过度;这将永远有效,但难以理解准确度降低

  3. 使用 BigInteger 而不是

  1. Divide by some known quantity (e.g. 1000) to avoid overflow; this reduces the accuracy by a known amount (in this case to the second) but will fail if you have more than 1000 items
  2. Divide each millis value by the number of dates you're averaging over; this will always work, but has hard-to-understand accuracy reduction
  3. Use BigInteger instead

方法1的一个例子:

long totalSeconds = 0L;
for (Date date : dates) {
     totalSeconds += date.getTime() / 1000L;
}
long averageSeconds = totalSeconds / dates.size();
Date averageDate = new Date(averageSeconds * 1000L);

方法3的示例:

BigInteger total = BigInteger.ZERO;
for (Date date : dates) {
     total = total.add(BigInteger.valueOf(date.getTime()));
}
BigInteger averageMillis = total.divide(BigInteger.valueOf(dates.size()));
Date averageDate = new Date(averageMillis.longValue());

这篇关于获取两个java.util.Date的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆