java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
A sample solution using java.time
, the modern Date-Time API:
Parse the start and end Date-Time strings into LocalDateTime
and iterate from the start to end checking the loop termination condition using LocalDateTime#isAfter
as shown below:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strStartDateTime = "2021-01-01 00:00:00";
String strEndDateTime = "2021-01-01 10:00:00";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime ldtStart = LocalDateTime.parse(strStartDateTime, dtf);
LocalDateTime ldtEnd = LocalDateTime.parse(strEndDateTime, dtf);
for (LocalDateTime ldt = ldtStart; !ldt.isAfter(ldtEnd); ldt = ldt.plusHours(1)) {
// System.out.println(ldt);
// Formatted
System.out.println(ldt.format(dtf));
// ...Your logic
}
}
}
Output:
2021-01-01 00:00:00
2021-01-01 01:00:00
2021-01-01 02:00:00
2021-01-01 03:00:00
2021-01-01 04:00:00
2021-01-01 05:00:00
2021-01-01 06:00:00
2021-01-01 07:00:00
2021-01-01 08:00:00
2021-01-01 09:00:00
2021-01-01 10:00:00
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.