Time series generation involves breaking a defined interval into equal spaced points. In Java, the java.time package provides a robust API for such operations. The focus here is on producing a list of timestamps between a given start and end using a fixed step.
Core Implementation
Start by importing the necessary classes from java.time and the collections framework:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
Define a method that accepts a start string, a end string, and a step in minutes. It returns a sequence of formatted timestamps:
public List<String> createTimePoints(String startStr, String endStr, long stepMinutes) {
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime cursor = LocalDateTime.parse(startStr, pattern);
LocalDateTime finish = LocalDateTime.parse(endStr, pattern);
List<String> points = new ArrayList<>();
while (cursor.isBefore(finish)) {
points.add(cursor.format(pattern));
cursor = cursor.plusMinutes(stepMinutes);
}
points.add(finish.format(pattern));
return points;
}
Usage Example
Call the method with a range and a 10‑minute interval, then print the results:
public static void main(String[] args) {
String from = "2022-01-01 00:00:00";
String to = "2022-01-01 01:00:00";
long gap = 10;
List<String> timeline = createTimePoints(from, to, gap);
timeline.forEach(System.out::println);
}
This produces a sequence such as 2022-01-01 00:00:00, 2022-01-01 00:10:00, …, 2022-01-01 01:00:00.
Handling Edge Cases
The implementation includes the end time and works correctly when the step does not divide the range evenly. For millisecond precision, switch to LocalDateTime arithmetic with java.time.Duration. The same logic applies: advance the cursor by the duration and collect formatted values.
Alternative Using Streams
A functional approach can generate the series using LongStream.iterate:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.stream.LongStream;
import java.util.stream.Collectors;
public List<String> streamTimeSeries(String startStr, String endStr, long stepMinutes) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime start = LocalDateTime.parse(startStr, fmt);
LocalDateTime end = LocalDateTime.parse(endStr, fmt);
long totalMinutes = java.time.Duration.between(start, end).toMinutes();
return LongStream.iterate(0, i -> i + stepMinutes)
.limit(totalMinutes / stepMinutes + 1)
.mapToObj(min -> start.plusMinutes(min).format(fmt))
.collect(Collectors.toList());
}
This yields the same output with concise stream operations. The example demonstrates both an explicit loop and a declarative pipeline, giving flexibility depending on coding style.