Search code examples
scalajava-timezoneddatetime

How to calculate the next minute and next 5 minute intevals given a ZonedDateTime


I have a instance of a ZonedDatetime.

ZonedDateTime.now(ZoneId.of("America/New_York"))

I basically need a function that will take an instance of a ZonedDateTime and return the next 1 minute and 5 minute values.

So if the current time is:

2021-10-24T19:46:10.649817

The next minute will be 19:47:00 and the next 5 minute will be 19:50:00

The next 5 minute interval is always like:

1:00
1:05
1:10
1:15
1:20
1:25
...
1:50
1:55
2:00

i.e. the next 5 minute interval is not based on exactly 5 minutes from now, but rather the next 5 minutes based on starting from the beginning of the hour. Same goes for the next 1 minute interval in the future.

def nextIntervals(zdt: ZonedDateTime): (ZonedDateTime, ZonedDateTime) = {
  ???
}

Solution

  • It is fairly simple to do so without hardcoding the values. Unfortunately I'm not familiar with scala so I'll give you some pseudo code, I believe you'll be able to easily translate it.

    nextIntervals(zdt) {
      timestamp = zdt.toUnixTimestamp();
    
      return [
        new ZonedDateTime(timestamp + (60 - timestamp % 60)),
        new ZonedDateTime(timestamp + (300 - timestamp % 300))
      ]
    }
    

    The above code assumes that ZonedDateTime can be instantiated by giving it a unix timestamp, measured in seconds. And also that it can be converted to a unix timestamp.

    The idea is pretty simple: the remainder of the modulus will be the time that has elapsed since the last required period (in your case 1 minute or 5 minutes). Take that away from the period itself and you have the time that's left until the next period. Add that to the current time and you have the exact datetime.

    Edit:

    Here's a working javascript example

    function nextIntervals(date) {
      let t = date.getTime();
    
      return [
        60e3,
        300e3,
      ].map(i => new Date(t + i - t % i));
    }
    
    console.log(nextIntervals(new Date));