本文介绍了如何将Joda库的DateTime循环到最近的X分钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将 DateTime Joda 库到最接近的 X 分钟? 例如:
How to round DateTime of Joda library to the nearest X minutes ? For example:
X = 10 minutes Jun 27, 11:32 -> Jun 27, 11:30 Jun 27, 11:33 -> Jun 27, 11:30 Jun 27, 11:34 -> Jun 27, 11:30 Jun 27, 11:35 -> Jun 27, 11:40 Jun 27, 11:36 -> Jun 27, 11:40 Jun 27, 11:37 -> Jun 27, 11:40推荐答案
接受的答案不正确处理设置了秒或毫秒的数据时间。为了完整,这里是一个正确处理的版本:
The accepted answer doesn't correctly handle datetimes that have seconds or milliseconds set. For completeness, here's a version that does handle that correctly:
private DateTime roundDate(final DateTime dateTime, final int minutes) { if (minutes < 1 || 60 % minutes != 0) { throw new IllegalArgumentException("minutes must be a factor of 60"); } final DateTime hour = dateTime.hourOfDay().roundFloorCopy(); final long millisSinceHour = new Duration(hour, dateTime).getMillis(); final int roundedMinutes = ((int)Math.round( millisSinceHour / 60000.0 / minutes)) * minutes; return hour.plusMinutes(roundedMinutes); }更多推荐
如何将Joda库的DateTime循环到最近的X分钟?
发布评论