【问题标题】:JodaTime rounding down to nearest quarter of hourJodaTime 四舍五入到最接近的一刻钟
【发布时间】:2014-03-17 01:40:49
【问题描述】:

如果时间是 10:36,我想将时间四舍五入到 10:30。如果时间是 1050,我想将时间四舍五入到 10:45。等等......我不知道该怎么做。有什么想法吗?

【问题讨论】:

  • 确定值(1045 和 1100)之间的中点,并确定当前值是否接近 1045 或 1100,相应调整...

标签: java jodatime


【解决方案1】:

这个怎么样?

public static LocalTime roundToQuarterHour(LocalTime time) {
  int oldMinute = time.getMinuteOfHour();
  int newMinute = 15 * (int) Math.round(oldMinute / 15.0);
  return time.plusMinutes(newMinute - oldMinute);
}

(由于有 withMinuteOfHour 方法,这可能看起来有点过于复杂,但请记住,我们可能会舍入到 60,而 withMinuteOfHour(60) 是无效的。)

【讨论】:

  • 看来他只是想四舍五入,所以你应该用Math.floor 来做这个。在这种情况下,您就没有 60 分钟的问题。
  • 感谢您在没有 java.time 的情况下提供的提示。如果您想向上取整到最近的 Quarter,那么您可以将 Math.floor 与您的代码组合使用:int newMinute = 15 * (int) Math.floor(oldMinute / 15.0);return time.plusMinutes(newMinute - oldMinute +15)
  • 这不是留下原始时间的秒部分吗?
【解决方案2】:

感谢您的回复。决定走这条路,不介绍 JodaTime。正如在这个答案中找到的How to round time to the nearest quarter hour in java?

    long timeMs = System.currentTimeMillis();       
    long roundedtimeMs = Math.round( (double)( (double)timeMs/(double)(15*60*1000) ) ) * (15*60*1000);

    Date myDt = new Date(roundedtimeMs);

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(myDt);

    if(calendar.before(new Date())) {
        calendar.add(Calendar.MINUTE, -15);
    }

    System.out.println(calendar.getTime());

【讨论】:

    【解决方案3】:
    public static LocalTime roundDown(LocalTime time, int toMinuteInterval) {
        int slotNo = (int)(time.getMillisOfDay() / ((double)toMinuteInterval * 60 * 1000));
        int slotsPerHour = 60 / toMinuteInterval;
        int h = slotNo / slotsPerHour;
        int m = toMinuteInterval * (slotNo % slotsPerHour);
        return new LocalTime(h, m);
    }
    

    仅当 toMinuteInterval 为 60 倍(例如 10、15、30 等)时才有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 2011-06-25
      • 1970-01-01
      • 2015-11-27
      • 1970-01-01
      • 2011-04-03
      相关资源
      最近更新 更多