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?
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.