1. import java.time.Instant;
  2. import java.time.LocalDateTime;
  3. import java.time.ZoneId;
  4. import java.time.ZonedDateTime;
  5. import java.time.format.DateTimeFormatter;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. public class TimestampSplitter {
  9. /**
  10. * Splits a list of timestamps into lists based on different levels of precision.
  11. *
  12. * @param timestamps A list of timestamps (represented as milliseconds since epoch).
  13. * @return A map where keys are precision levels (e.g., "year", "month", "day")
  14. * and values are lists of timestamps at that precision. Returns an empty map if input is null or empty.
  15. */
  16. public static List<List<Long>> splitTimestamps(List<Long> timestamps) {
  17. if (timestamps == null || timestamps.isEmpty()) {
  18. return new ArrayList<>();
  19. }
  20. List<List<Long>> result = new ArrayList<>();
  21. // Split by year
  22. List<Long> yearlyTimestamps = new ArrayList<>();
  23. for (Long timestamp : timestamps) {
  24. Instant instant = Instant.ofEpochMilli(timestamp);
  25. ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
  26. yearlyTimestamps.add(zonedDateTime.toLocalDateTime().toInstant().toEpochMilli());
  27. }
  28. result.add(yearlyTimestamps);
  29. // Split by month
  30. List<Long> monthlyTimestamps = new ArrayList<>();
  31. for (Long timestamp : timestamps) {
  32. Instant instant = Instant.ofEpochMilli(timestamp);
  33. ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
  34. monthlyTimestamps.add(zonedDateTime.toLocalDate().toInstant().toEpochMilli());
  35. }
  36. result.add(monthlyTimestamps);
  37. // Split by day
  38. List<Long> dailyTimestamps = new ArrayList<>();
  39. for (Long timestamp : timestamps) {
  40. Instant instant = Instant.ofEpochMilli(timestamp);
  41. ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
  42. dailyTimestamps.add(zonedDateTime.toLocalDate().toInstant().toEpochMilli());
  43. }
  44. result.add(dailyTimestamps);
  45. return result;
  46. }
  47. public static void main(String[] args) {
  48. //Example Usage
  49. List<Long> timestamps = List.of(
  50. 1678886400000L, // March 15, 2023
  51. 1678972800000L, // March 16, 2023
  52. 1679059200000L, // March 17, 2023
  53. 1704000000000L, // January 1, 2024
  54. 1704006000000L //January 2, 2024
  55. );
  56. List<List<Long>> splitData = splitTimestamps(timestamps);
  57. for (int i = 0; i < splitData.size(); i++) {
  58. System.out.println("Timestamps for " + getPrecision(i) + ": " + splitData.get(i));
  59. }
  60. }
  61. private static String getPrecision(int index) {
  62. switch (index) {
  63. case 0: return "Year";
  64. case 1: return "Month";
  65. case 2: return "Day";
  66. default: return "Unknown";
  67. }
  68. }
  69. }

Add your comment