CommonTimeUtil { public static long timeToBucket(final long time, final TimeBucket bucket) { final OffsetDateTime dateTime = Instant.ofEpochMilli(time).atOffset(ZoneOffset.UTC); final long timeBucket; switch (bucket) { case MILLISECOND: timeBucket = dateTime.truncatedTo(MILLIS).toInstant().toEpochMilli(); break; case SECOND: timeBucket = dateTime.truncatedTo(SECONDS).toInstant().toEpochMilli(); break; case MINUTE: timeBucket = dateTime.truncatedTo(MINUTES).toInstant().toEpochMilli(); break; case HOUR: timeBucket = dateTime.truncatedTo(HOURS).toInstant().toEpochMilli(); break; case DAY: timeBucket = dateTime.truncatedTo(DAYS).toInstant().toEpochMilli(); break; case WEEK: timeBucket = dateTime.with(firstDayOfWeek()).truncatedTo(DAYS).toInstant().toEpochMilli(); break; case MONTH: timeBucket = dateTime.with(firstDayOfMonth()).truncatedTo(DAYS).toInstant().toEpochMilli(); break; case YEAR: timeBucket = dateTime.with(firstDayOfYear()).truncatedTo(DAYS).toInstant().toEpochMilli(); break; default: timeBucket = time; } return timeBucket; } private  CommonTimeUtil(); static long timeToBucket(final long time, final TimeBucket bucket); static final long MILLISECONDS_IN_SECOND; static final long MILLISECONDS_IN_MINUTE; static final long MILLISECONDS_IN_HOUR; static final long MILLISECONDS_IN_DAY; }
@Test public void shouldCorrectlyPlaceTimestampsIntoBuckets() { final OffsetDateTime offsetDateTime = OffsetDateTime.parse("2000-01-01T12:34:56.789Z"); final long time = offsetDateTime.toInstant().toEpochMilli(); final OffsetDateTime yearOffsetDateTime = OffsetDateTime.parse("2000-02-03T12:34:56.789Z"); final long yearTime = yearOffsetDateTime.toInstant().toEpochMilli(); assertEquals(parse("2000-01-01T12:34:56.789Z").toInstant().toEpochMilli(), timeToBucket(time, MILLISECOND)); assertEquals(parse("2000-01-01T12:34:56.000Z").toInstant().toEpochMilli(), timeToBucket(time, SECOND)); assertEquals(parse("2000-01-01T12:34:00.000Z").toInstant().toEpochMilli(), timeToBucket(time, MINUTE)); assertEquals(parse("2000-01-01T12:00:00.000Z").toInstant().toEpochMilli(), timeToBucket(time, HOUR)); assertEquals(parse("2000-01-01T00:00:00.000Z").toInstant().toEpochMilli(), timeToBucket(time, DAY)); assertEquals(parse("1999-12-27T00:00:00.000Z").toInstant().toEpochMilli(), timeToBucket(time, WEEK)); assertEquals(parse("2000-01-01T00:00:00.000Z").toInstant().toEpochMilli(), timeToBucket(time, MONTH)); assertEquals(parse("2000-01-01T00:00:00.000Z").toInstant().toEpochMilli(), timeToBucket(yearTime, YEAR)); }