Get specific 15 minute time frames based on current time

I would like to get a 15 minute timeframe based on the current time.

For instance:

Time interval for every 15 minutes.

ie 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 12:34means, I need to return the timeframe as12:31 to 12:45

Is this something we can do easily with the Java 8 date and time API?

+4
source share
2 answers

You can create TemporalAdjusterone that calculates the end of the current 15 minute period and calculates the beginning of the period by removing 14 minutes.

It might 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.

. , DST - .

+5

API Date . (15 ) . 15- . , . . :

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        long ms = new Date().getTime();
        System.out.println("Current time: " + new Date().toString());

        long fifteen = 15 * 60 * 1000;
        long newMs = (ms / fifteen) * fifteen + fifteen;
        System.out.println("Calculated time: " + new Date(newMs));
    }
}

.

:

LocalDate

import java.util.*;
import java.lang.*;
import java.io.*;
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        LocalTime now = LocalTime.now();
        System.out.println(now);

        LocalTime next = now.with((temp) -> {
            int currentMinute = temp.get(ChronoField.MINUTE_OF_DAY);
            int interval = (currentMinute / 15) * 15 + 15;
            temp = temp.with(ChronoField.SECOND_OF_MINUTE, 0);
            temp = temp.with(ChronoField.MILLI_OF_SECOND, 0);
            return temp.with(ChronoField.MINUTE_OF_DAY, interval);  
        });
        System.out.println(next);
    }
}
+3

Source: https://habr.com/ru/post/1665583/


All Articles