【问题标题】:Different SimpleDateFormat parsen不同的 SimpleDateFormat 解析
【发布时间】:2019-09-20 15:02:30
【问题描述】:

我想检查日期是否与我定义的模式之一匹配。请看下面我的代码。

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”(因此是列表中的第一个)。如果我有任何其他模式,它会显示一个异常......

你能帮帮我吗?我写错了哪一行?

【问题讨论】:

  • 你遇到了什么异常?也许抓住并忽略那个?
  • 不,它只是检查我的 var 是否具有第一个模式而不是其他模式...如果它没有第一个模式,则直接进入异常
  • 日期是一个日期。它不能匹配或不匹配模式。日期的字符串表示可能与模式匹配。我认为这是正则表达式应用程序的一种任务。
  • 我怀疑你想要return dateType; inside try 块 - 否则即使第一个成功,你也在尝试所有模式。
  • 仅供参考,您使用的日期时间类在几年前被 JSR 310 中定义的 java.time 类所取代。请参阅DateTimeFormatterDateTimeFormatterBuilder

标签: java date validation simpledateformat


【解决方案1】:

避免使用旧的日期时间类

您正在使用糟糕的日期时间类,这些类在几年前被 JSR 310 定义的行业领先的现代 java.time 类所取代。

java.time

改用LocalDateDateTimeFormatter

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

23.01.2020 ➙ 2020-01-23

20200123 ➙ 2020-01-23

2020/01/23 ➙ 2020-01-23

23/01/2020 ➙ 2020-01-23

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    相关资源
    最近更新 更多