fork download
  1. import java.time.LocalDate;
  2. import java.time.MonthDay;
  3. import java.time.format.DateTimeFormatter;
  4. import java.time.format.DateTimeFormatterBuilder;
  5. import java.time.temporal.ChronoField;
  6. import java.util.Locale;
  7.  
  8. class Main {
  9. public static void main(String args[]) {
  10. // If your string is in --MM-dd format
  11. MonthDay monthDay = MonthDay.parse("--03-10");
  12. // If you want the current year, replace 1 with Year.now().getValue()
  13. LocalDate date = monthDay.atYear(1);
  14. System.out.println(date);
  15.  
  16. // If your string is in MM-dd format
  17. DateTimeFormatter monthDayFormatter = DateTimeFormatter.ofPattern("MM-dd", Locale.ENGLISH);
  18. monthDay = MonthDay.parse("03-10", monthDayFormatter);
  19. // If you want the current year, replace 1 with Year.now().getValue()
  20. date = monthDay.atYear(1);
  21. System.out.println(date);
  22.  
  23. // An alternative solution
  24. DateTimeFormatter dtf = new DateTimeFormatterBuilder()
  25. .appendPattern("MM-dd")
  26. // If you want the current year, replace 1 with Year.now().getValue()
  27. .parseDefaulting(ChronoField.YEAR, 1)
  28. .toFormatter(Locale.ENGLISH);
  29. date = LocalDate.parse("03-10", dtf);
  30. System.out.println(date);
  31. }
  32. }
Success #stdin #stdout 0.12s 49432KB
stdin
Standard input is empty
stdout
0001-03-10
0001-03-10
0001-03-10