如何检查用户是否在java中插入了这种格式的日期周数和年份的最后两位数字



我想检查用户是否以这种格式插入日期
例如:String date="1420〃;;其中14是一年中的周数,20是2020年

我已经创建了这个方法,但它不起作用。正确的模式是什么?你也可以给我分享一个链接或其他东西,在那里我可以看到这些模式。

public static boolean checkDate (String date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("wwuu");
try {
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
System.out.println("The string is a date and time: " + dateTime);
return true;
} catch (DateTimeParseException dtpe) {
System.out.println("The string is not a date and time of format "wwuu" : " + dtpe.getMessage());
return false;
}
}

我收到这个消息该字符串不是格式为"的日期和时间;wwuu":无法分析文本"1420":无法从TemporalAccess获取LocalDateTime:{WeekOfWeekBasedYear[WeekFields[SUNDAY,1]]=14,Year=2020},java.time.format.parsed 类型的ISO

使用'u'指定年份似乎不起作用。相反,您应该使用"Y"。根据文献;基于周的年";(https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html(。

但是格式化程序仍然存在问题。通过指定一周和一年,解析器无法知道在解析日期时应该考虑一周中的哪一天和一天中的哪时间。您可以使用DateTimeFormatterBuilder为不在要格式化的字符串中的内容指定默认值。这是您的代码改编:

public static boolean checkDate (String date) {
DateTimeFormatter formatter =  new DateTimeFormatterBuilder().appendPattern("wwYY")
.parseDefaulting(WeekFields.ISO.dayOfWeek(), DayOfWeek.MONDAY.getValue())
.toFormatter();
try {
LocalDateTime dateTime = LocalDate.parse(date, formatter).atStartOfDay();
System.out.println("The string is a date and time: " + dateTime);
return true;
} catch (DateTimeParseException dtpe) {
System.out.println("The string is not a date and time of format "wwuu" : " + dtpe.getMessage());
return false;
}
}

我将格式化程序定义为使用星期一作为一周中的默认日期。然后我只格式化了LocalDate,并指定我想要这个日期";atStartOfDay";。

最新更新