Search code examples
javadateautoformatting

Java Autocomplete/Format Date from MM-DD input


Is there a way to auto complete a date in YYYY-MM-DD format where the input field would only require MM-DD.

The year would be the current year unless the month and day were in the past.

Example:

Input of "06-28" would output 2017-06-28

and if the date was in the past,

Input "04-30" output 2018-04-30

The code would be written in HTML or Java

Thanks for the help and sorry if I am missing something.


Solution

  • This is where the java.time classes excel.

    public static LocalDate autocomplete(String mmdd) {
        ZoneId clientTimeZone = ZoneId.systemDefault();
        LocalDate today = LocalDate.now(clientTimeZone);
        MonthDay md = MonthDay.parse(mmdd, DateTimeFormatter.ofPattern("MM-dd"));
        Year y = Year.from(today);
        if (md.isBefore(MonthDay.from(today))) {
            // in the past; use next year
            y = y.plusYears(1);
        }
        return y.atMonthDay(md);
    }
    

    Please note the dependency on time zone. Think twice about which zone you should use.

    If you need the result as a String, just use toString().

    Corner case: The method will accept 02-29 as valid input and will autocomplete into a date of February 28 if the chosen year is not a leap year. You may want to modify it to reject 02-29 unless next February has 29 days.