Java Autocomplete/Format Date from MM-DD input

泪湿孤枕 提交于 2019-12-13 12:54:24

问题


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.


回答1:


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.




回答2:


Why not just write a simple function that checks the current date and based on that autocompletes the year?



来源:https://stackoverflow.com/questions/43858077/java-autocomplete-format-date-from-mm-dd-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!