JodaTime rounding down to nearest quarter of hour

左心房为你撑大大i 提交于 2019-12-23 21:08:00

问题


If the time is 10:36 I would like to round the time down to 10:30. If the time is 1050 I would like to round the time down to 10:45. etc... I am not sure how to do this. Any ideas?


回答1:


How about this?

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

(It may seem slightly overcomplicated since there's a withMinuteOfHour method, but keep in mind that we might round to 60, and withMinuteOfHour(60) is invalid.)




回答2:


Thanks for the responses. Decided to go this route and not introduce JodaTime. As found in this answer 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);
}

Only works when toMinuteInterval is a factor of 60 (eg 10, 15, 30 etc).



来源:https://stackoverflow.com/questions/22445573/jodatime-rounding-down-to-nearest-quarter-of-hour

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!