Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the specific 15 minutes timeframe based on current time

I would like to get the 15 minutes timeframe based on Current Time.

For example:

Timeframe is for every 15 minutes.

i.e 12 to 1 is divided into four timeframes [ 12:00 to 12:15, 12:16 to 12:30, 1:31 to 12:45, 12:46 to 1:00]

If the current time is 12:34 means, i need to return the timeframe as 12:31 to 12:45

Is it something we can do easily with Java 8 Date and Time API?

like image 763
Shankar Avatar asked Dec 24 '22 22:12

Shankar


1 Answers

You could create a TemporalAdjuster that calculates the end of the current 15-minute period and calculate the start of the period by removing 14 minutes.

Could look like this:

public static void main(String[] args) {
  LocalTime t = LocalTime.of(12, 34);
  LocalTime next15 = t.with(next15Minute());
  System.out.println(next15.minusMinutes(14) + " - " + next15);
}

public static TemporalAdjuster next15Minute() {
  return (temporal) -> {
    int minute = temporal.get(ChronoField.MINUTE_OF_DAY);
    int next15 = (minute / 15 + 1) * 15;
    return temporal.with(ChronoField.NANO_OF_DAY, 0).plus(next15, ChronoUnit.MINUTES);
  };
}

which outputs 12:31 - 12-45.

Note: I'm not sure how it behaves around DST changes - to be tested.

like image 60
assylias Avatar answered Dec 26 '22 12:12

assylias