我试图实现这一目标:我有一个方法,它接收一个日期模式格式的字符串(例如“dd/mm/yyyy”),并且该方法必须验证该模式在 java 中是否有效。 例如,假设我有以下输入:
String input1="dd/mm/yyyy";
String input2="mm/dd/yyyy";
String input3"cceq.der.sads";
String input4= "dd-M-yyyy hh:mm:ss"
public Boolean validPatternDate(String in){
//The code im looking for
}
应用于 validPatternDate 方法的每个输入的结果将是:
input1 True
input2 True
input3 False
input4 True
有没有办法在java中做到这一点?谢谢
最佳答案
tl;dr
在捕获 IllegalArgumentException
时尝试 DateTimeFormatter.ofPattern
。
try {
formatter = DateTimeFormatter.ofPattern( input ) ;
} catch ( IllegalArgumentException e ) {
… // Handle exception thrown for invalid input formatting pattern.
}
更好的是,让 DateTimeFormatter.ofLocalized...
自动本地化,而不是尝试允许麻烦的任意格式字符串。
本地化,而不是
接受任何任意的格式化模式都会是一个令人头痛的问题。格式化模式复杂而微妙。
此外,许多格式还要求您指定区域设置
,以确定决定月份名称和星期名称翻译等问题所需的人类语言和文化规范等等、缩写、大写、标点符号等等。
我建议您让java.time本地化。您可以传递 FormatStyle
而不是传递格式模式。枚举对象(或其名称的字符串)和 Locale
目的。但正如我上面提到的,在任何情况下您都需要传递 Locale
。
使用 FormatStyle
和 Locale
获取本地化 DateTimeFormatter
对象。
FormatStyle style = FormatStyle.MEDIUM ;
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) ;
LocalDate localDate = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
String output = localDate.format( formatter ) ;
查看此code run live at IdeOne.com .
12 juill. 2021
陷阱 IllegalArgumentException
如果您坚持接受任意格式模式的方法,您可以尝试在 DateTimeFormatter
类中使用该格式。调用其 ofPattern
方法。 IllegalArgumentException
的陷阱如果模式无效则抛出。
String input = "dd/mm/yyyy" ;
DateTimeFormatter f = null ;
try {
formatter = DateTimeFormatter.ofPattern( input ) ;
} catch ( IllegalArgumentException e ) {
… // Handle exception thrown for invalid input formatting pattern.
}
注意:如上所述,某些格式需要 Locale
。因此,您应该接收区域设置参数以及格式模式,并调用 DateTimeFormatter.withLocale
.
关于java - 如何检查java中的日期模式是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68352829/