I want to be able to round any given Instant to the nearest Period to support grouping of data.
i.e. someone might want to group by 2 week periods, so given an Instant, I want to be able to work out the nearest instant (before or after) on the period boundary where "now" is considered to be the end of the current period. If today is Tuesday, then consider that this 2 week Period ends this week. Given any date (from now backward) I'd like to calculate the "2 week Period" that it fits in to.
// 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 that makes sense, any help or pointers greatly appreciated.
The answer is yes, under specific rules. The U.S. Federal Law states that employers are allowed to round the time to specific predetermined time intervals: nearest 5 minutes, nearest 10th of an hour (6 minutes), or quarter of an hour (15 minutes).
Round time to nearest hour ( TIME(1,0,0) = 1/24 representing an hour) and add a zero time value to ensure the expression is cast as a Time. M: There isn't an equivalent of MROUND in M, so instead multiply the time by 24 to express it as a number of hours, then round, then divide by 24 and convert to a Time type.
In order to round a DateTime object to the nearest minute, you need to use the round operation from Pandas on the DateTime column and specify the frequency that you want to use. For rounding to the nearest minute you will need to use round("min") .
Ok, this is one solution I made myself but I really think 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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With