-2

I need to know if a date match a periodicity, for example, periodicity is 1 hour, and date that user gives is 13/09/2021 23:00, the inicial that my java code should take is 13/09/2021 00:00 and check how many times have to add 1 hour to get the date 13/09/2021 23:00.

The idea now is made a loop and add 1hour to the date and save in an array, then check if the date is inside the array and the position. Is there any other way?

wty
  • 21
  • 5

2 Answers2

1

If I understand your question correctly, you just want to calculate how many hours there are between two dates. For that, it's cleaner to use the built-in java.time classes. You can read the two dates into LocalDateTime objects and calculate the time span between them with ChronoUnit.HOURS:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
LocalDateTime start = LocalDateTime.parse("13/09/2021 00:00", formatter);
LocalDateTime end = LocalDateTime.parse("13/09/2021 23:00", formatter);
long hours = ChronoUnit.HOURS.between(start, end);

The result will be 23.

For various other units (minutes for example), there's ChronoUnit.MINUTES. Have a look at the documentation. There are a lot of different units to choose from.

QBrute
  • 4,405
  • 6
  • 34
  • 40
  • I think It can help me , going to see if ChronoUnit.Minutes is also available then i divide by 5,10 or 15 and I have the times from the original date. Thanks – wty Sep 13 '21 at 21:49
1

I am adding a couple of minor refinements compared to the correct answer by QBrute.

  1. The periodicity can be any amount of time in hours, minutes and seconds.

  2. I am taking time zone into account so we also get correct results across summer time transitions (spring forward and fall back) and other time anomalies.

  3. If there isn’t a whole number of periodicities, I am rounding up to be sure to have at least enough.

    ZoneId userTimeZone = ZoneId.of("Africa/Dar_es_Salaam");
    
    Duration periodicity = Duration.ofMinutes(5);
    ZonedDateTime userTime = ZonedDateTime.of(2021, 9, 13, 23, 0, 0, 0, userTimeZone);
    ZonedDateTime initialTime = ZonedDateTime.of(2021, 9, 13, 0, 0, 0, 0, userTimeZone);
    
    Duration timeBetween = Duration.between(initialTime, userTime);
    long numberOfPeriodicities = timeBetween.dividedBy(periodicity);
    // Has truncation occurred?
    if (initialTime.plus(periodicity.multipliedBy(numberOfPeriodicities)).isBefore(userTime)) {
        // Need one more periodicity
        numberOfPeriodicities++;
    }
    
    System.out.println(numberOfPeriodicities);
    

Output is:

276

If you want a periodicity of 7.5 minutes, specify Duration.ofMinutes(7).plusSeconds(30). The Duration.dividedBy(Duration) method that I am using was introduced in Java 9.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161