How do I truncate / defer a date to an interval?
I tried to truncate dates using Instant.truncatedTo, but it doesn't seem to allow more than one day to be truncated. What I want to do is truncate dates using a specific time interval. For example:
For 1hour interval, 2014-10-18T11:30:52.560Z should become: 2014-10-18T11:00:00.000Z
For 1day interval, 2014-10-18T11:30:52.560Z should become: 2014-10-18T00:00:00.000Z
For 1month interval, 2014-10-18T11:30:52.560Z should become: 2014-10-01T00:00:00.000Z
For 6month interval, 2014-10-18T11:30:52.560Z should become: 2014-07-01T00:00:00.000Z
Therefore, it is more like including dates at a specific time interval.
I did use the timestamp values to separate them into time intervals ((dateTimestamp / intervalTimestamp) * intervalTimestamp), but there are no fixed timestamp values when using months, because the days of the months can change so they don't work for months.
+3
source to share
1 answer
You can write your own function:
public LocalDateTime truncateTo(LocalDateTime dt, Time interval) {
switch(interval) {
case MONTH_6:
if(dt.getMonthValue() > 6)
dt = dt.withMonth(7);
else
dt = dt.withMonth(1);
case MONTH:
dt = dt.withDayOfMonth(1);
case DAY:
dt = dt.withHour(0);
case HOUR:
dt = dt.withMinute(0);
dt = dt.withSecond(0);
dt = dt.withNano(0);
break;
}
return dt;
}
+1
source to share