我想检查日期是否与我定义的模式之一匹配。请看下面我的代码。
date = null
List<String> formatStrings = Arrays.asList("yyyy-MM-dd", "dd.MM.yyyy", "yyyyMMdd", "yyyy/MM/dd", "dd/MM/yyyy");
for (String formatStr: formatStrings) {
try {
dateType = new Date(new SimpleDateFormat(formatStr).parse(myCol).getTime());
} catch (ParseException e) {}
}
return date;
我也尝试过:
try {
for.. }
catch {}
我还编写了一个单元测试来测试我的函数是否正常工作,但是仅当我的变量具有以下模式时才有效:“ yyyy-MM-dd”(因此列表中的第一个)。如果我有任何其他模式,则显示异常...
你能帮我么?我写错了哪一行?
最佳答案
避免使用旧的日期时间类
您使用的是可怕的日期时间类,而这些类早已被JSR 310定义的行业领先的现代java.time类所取代。
java.time
切换为使用LocalDate
和DateTimeFormatter
。DateTimeFormatter
预定义了您期望的几种格式,每种都是标准ISO 8601格式的变体。对于其他三种格式,我们定义了一种格式化模式。
package work.basil.example;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Objects;
public class Demo
{
public static void main ( String[] args )
{
Demo app = new Demo ();
app.demo ();
}
private void demo ( )
{
// ("yyyy-MM-dd", "dd.MM.yyyy", "yyyyMMdd", "yyyy/MM/dd", "dd/MM/yyyy"
final List < DateTimeFormatter > formatterList = List.of (
DateTimeFormatter.ISO_LOCAL_DATE ,
DateTimeFormatter.ofPattern ( "dd.MM.uuuu" ) ,
DateTimeFormatter.BASIC_ISO_DATE ,
DateTimeFormatter.ofPattern ( "uuuu/M/dd" ) ,
DateTimeFormatter.ofPattern ( "dd/MM/uuuu" )
);
final List < String > inputs = List.of ( "2020-01-23" , "23.01.2020" , "20200123" , "2020/01/23" , "23/01/2020" );
for ( String input : inputs )
{
LocalDate localDate = null;
for ( DateTimeFormatter formatter : formatterList )
{
try
{
localDate = LocalDate.parse ( input , formatter );
if ( ! localDate.equals ( LocalDate.of ( 2020 , Month.JANUARY , 23 ) ) )
{
throw new IllegalStateException ( "Oops! Unexpected result. " + input + " ➙ " + localDate );
}
System.out.println ( input + " ➙ " + localDate );
break; // Bail out of this inner FOR loop, as we have successfully parsed this input.
} catch ( DateTimeParseException e )
{
// Swallow exception, as we expect most to fail.
}
}
Objects.requireNonNull ( localDate , "Oops, unexpected input: " + input );
}
}
}
参见此code run live at IdeOne.com。
2020-01-23➙2020-01-23
2020年1月23日➙2020-01-23
20200123➙2020-01-23
2020/01/23➙2020-01-23
2020年1月23日➙2020-01-23
关于java - 不同的SimpleDateFormat解析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58030906/