fork download
  1. import java.time.LocalDate;
  2. import java.time.LocalTime;
  3. import java.time.ZoneId;
  4. import java.time.ZonedDateTime;
  5. import java.time.format.DateTimeFormatter;
  6. import java.time.temporal.ChronoField;
  7. import java.time.temporal.TemporalAdjusters;
  8. import java.util.Locale;
  9.  
  10. class Main {
  11. public static void main(String[] args) {
  12. // Replace ZoneId.systemDefault() with the applicable ZoneId e.g.
  13. // ZoneId.of("America/New_York")
  14. ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault());
  15. System.out.println(zdt);
  16.  
  17. zdt = zdt.with(TemporalAdjusters.firstDayOfMonth());
  18. System.out.println(zdt);
  19.  
  20. zdt = zdt.withHour(LocalTime.MIN.getHour());
  21. System.out.println(zdt);
  22.  
  23. zdt = zdt.withMinute(LocalTime.MIN.getMinute());
  24. System.out.println(zdt);
  25.  
  26. zdt = zdt.withSecond(LocalTime.MIN.getSecond());
  27. System.out.println(zdt);
  28.  
  29. zdt = zdt.with(ChronoField.MILLI_OF_SECOND, LocalTime.MIN.getLong(ChronoField.MILLI_OF_SECOND));
  30. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
  31. System.out.println(zdt.format(formatter));
  32.  
  33. // In a single statement
  34. String output = ZonedDateTime.now(ZoneId.systemDefault())
  35. .with(TemporalAdjusters.firstDayOfMonth())
  36. .withHour(LocalTime.MIN.getHour())
  37. .withMinute(LocalTime.MIN.getMinute())
  38. .withSecond(LocalTime.MIN.getSecond())
  39. .with(ChronoField.MILLI_OF_SECOND, LocalTime.MIN.getLong(ChronoField.MILLI_OF_SECOND))
  40. .format(formatter);
  41. System.out.println(output);
  42.  
  43. // There is a better way if all you want is day-1 with minimum time
  44. zdt = LocalDate.now(ZoneId.systemDefault())
  45. .with(TemporalAdjusters.firstDayOfMonth())
  46. .atStartOfDay()
  47. .atZone(ZoneId.systemDefault());
  48. System.out.println(zdt.format(formatter));
  49. }
  50. }
Success #stdin #stdout 0.13s 49468KB
stdin
Standard input is empty
stdout
2023-01-19T16:50:43.811714Z[GMT]
2023-01-01T16:50:43.811714Z[GMT]
2023-01-01T00:50:43.811714Z[GMT]
2023-01-01T00:00:43.811714Z[GMT]
2023-01-01T00:00:00.811714Z[GMT]
2023-01-01T00:00:00.000Z
2023-01-01T00:00:00.000Z
2023-01-01T00:00:00.000Z