How to round DateTime to the nearest period

I want to be able to round any given moment to the nearest period to support data grouping.

i.e. someone may want to group for 2 weeks, so Instant, I want to be able to work in the near future (before or after) at the border of the period where β€œnow” is considered the end of the current period. If today is Tuesday, then think that this 2 week ends this week. Given any date (now back), I would like to calculate the β€œ2-week period” in which it fits.

// pseudo code Period sevenDays = Days.SEVEN; Instant nearestWeek = sevenDays.roundToNearest(new DateTime()); Period twelveHours = Hours.hours(12); Instant nearestHalfDay = twelveHours.roundToNearest(new DateTime()); 

I hope this makes sense, any help or pointers are much appreciated.

+7
source share
1 answer

Ok, this is one of the solutions I made myself, but I really think that this functionality should be built into Joda Time.

 public static DateTime dateTimeFloor(DateTime dt, Period p) { if (p.getYears() != 0) { return dt.yearOfEra().roundFloorCopy().minusYears(dt.getYearOfEra() % p.getYears()); } else if (p.getMonths() != 0) { return dt.monthOfYear().roundFloorCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths()); } else if (p.getWeeks() != 0) { return dt.weekOfWeekyear().roundFloorCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks()); } else if (p.getDays() != 0) { return dt.dayOfMonth().roundFloorCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays()); } else if (p.getHours() != 0) { return dt.hourOfDay().roundFloorCopy().minusHours(dt.getHourOfDay() % p.getHours()); } else if (p.getMinutes() != 0) { return dt.minuteOfHour().roundFloorCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes()); } else if (p.getSeconds() != 0) { return dt.secondOfMinute().roundFloorCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds()); } return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis()); } 
+8
source

All Articles