本文介绍了MM-DD输入中的Java自动完成/格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

有没有一种方法可以自动完成YYYY-MM-DD格式的日期,而输入字段只需要MM-DD.

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.

示例:

输入"06-28"将输出2017-06-28

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

如果日期是过去的时间,

and if the date was in the past,

输入"04-30"输出2018-04-30

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

代码将以HTML或Java编写

The code would be written in HTML or Java

感谢您的帮助,如果我错过了某些事情,我们深表歉意.

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

推荐答案

这是 java.time 类很出色.

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.

如果需要将结果作为String,只需使用toString().

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

正确的情况:该方法将接受02-29作为有效输入,并且如果所选的年份不是a年,则该方法将自动完成到2月28日.除非明年二月有29天,否则您可能需要对其进行修改以拒绝02-29.

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.

这篇关于MM-DD输入中的Java自动完成/格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:17