import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class TimestampSplitter {
/**
* Splits a list of timestamps into lists based on different levels of precision.
*
* @param timestamps A list of timestamps (represented as milliseconds since epoch).
* @return A map where keys are precision levels (e.g., "year", "month", "day")
* and values are lists of timestamps at that precision. Returns an empty map if input is null or empty.
*/
public static List<List<Long>> splitTimestamps(List<Long> timestamps) {
if (timestamps == null || timestamps.isEmpty()) {
return new ArrayList<>();
}
List<List<Long>> result = new ArrayList<>();
// Split by year
List<Long> yearlyTimestamps = new ArrayList<>();
for (Long timestamp : timestamps) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
yearlyTimestamps.add(zonedDateTime.toLocalDateTime().toInstant().toEpochMilli());
}
result.add(yearlyTimestamps);
// Split by month
List<Long> monthlyTimestamps = new ArrayList<>();
for (Long timestamp : timestamps) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
monthlyTimestamps.add(zonedDateTime.toLocalDate().toInstant().toEpochMilli());
}
result.add(monthlyTimestamps);
// Split by day
List<Long> dailyTimestamps = new ArrayList<>();
for (Long timestamp : timestamps) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
dailyTimestamps.add(zonedDateTime.toLocalDate().toInstant().toEpochMilli());
}
result.add(dailyTimestamps);
return result;
}
public static void main(String[] args) {
//Example Usage
List<Long> timestamps = List.of(
1678886400000L, // March 15, 2023
1678972800000L, // March 16, 2023
1679059200000L, // March 17, 2023
1704000000000L, // January 1, 2024
1704006000000L //January 2, 2024
);
List<List<Long>> splitData = splitTimestamps(timestamps);
for (int i = 0; i < splitData.size(); i++) {
System.out.println("Timestamps for " + getPrecision(i) + ": " + splitData.get(i));
}
}
private static String getPrecision(int index) {
switch (index) {
case 0: return "Year";
case 1: return "Month";
case 2: return "Day";
default: return "Unknown";
}
}
}
Add your comment