如何将给定的Day + Month(以String形式)转换为与该Day + month相匹配的最新日期,例如“ 21.1”。分为2018年1月21日和“ 13.1”。到13-01-2019。
我现在正在使用此不建议使用的解决方案:
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Date currentDate = new Date();
Date date = df.parse(input + "2016"); // else the 29.02. is never recognized, because in the default parse year 1970 it doesn't exist.
date.setYear(currentDate.getYear()); // deprecated
if (date.compareTo(currentDate) > 0) {
date.setYear(currentDate.getYear() - 1);
}
return date;
答案 0 :(得分:2)
这是使用LocalDate
和DateTimeFormatter
而不是较旧类的版本
public LocalDate getDate(String input) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.M.yyyy");
LocalDate now = LocalDate.now();
LocalDate date = LocalDate.parse(String.format("%s.%d", input, now.get(ChronoField.YEAR)), dtf);
if (date.compareTo(now) > 0) {
date = date.minusYears(1);
}
return date;
}
下面是一个版本,如果input
为“ 29.2”,它将选择2月29日之前的版本,我仅对其进行了简短测试,但似乎可以使用。
public static LocalDate getDate(String input) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.M.yyyy");
LocalDate now = LocalDate.now();
boolean is29 = input.equals("29.2");
LocalDate date = LocalDate.parse(String.format("%s.%d", input, now.get(ChronoField.YEAR)), dtf);
if (date.compareTo(now) > 0) {
date = date.minusYears(1);
}
if (is29 && !date.isLeapYear()) {
do {
date = date.minusYears(1);
} while (!date.isLeapYear());
date = date.plusDays(1); //move from 28th to 29th
}
return date;
}
答案 1 :(得分:0)
我建议使用Calendar
摆脱弃用的解决方案:
static Date getDate(String input) throws ParseException {
DateFormat df = new SimpleDateFormat("dd.MM");
Calendar currentDate = Calendar.getInstance();
Calendar date = Calendar.getInstance();
date.setTime(df.parse(input));
date.set(Calendar.YEAR, currentDate.get(Calendar.YEAR));
if (date.after(currentDate)) {
date.set(Calendar.YEAR, currentDate.get(Calendar.YEAR) - 1);
}
return date.getTime();
}
答案 2 :(得分:0)
有一个java.time.MonthDay
类,它与LocalDate类似,但是没有年份:
MonthDay md = MonthDay.parse(input, DateTimeFormatter.ofPattern("dd.MM."));
MonthDay today = MonthDay.now();
if (md.isAfter(today)) {
return Year.now().minusYears(1).atMonthDay(md);
} else {
return Year.now().atMonthDay(md);
}