Java apache DateUtils:解析具有多种模式的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26712834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:08:18  来源:igfitidea点击:

apache DateUtils: parsing a date with multiple patterns

javaparsingdateapache-commons

提问by dao hodac

I want to parse a date that has different potential formats using DateUtils.parseDate. It seems to use the first parser, even if it should detect the difference between 23/10/2014and 2014/10/23.

我想使用DateUtils.parseDate. 看来使用第一语法分析器,即使它应该检测之间的差异23/10/20142014/10/23

It actually parses the date even if it is wrong, so that I can't even catch an exception. How can I do? Is it a bug? (commons-lang3-3.3.2)

即使日期错误,它实际上也会解析日期,因此我什至无法捕获异常。我能怎么做?这是一个错误吗?(commons-lang3-3.3.2)

Here is a code snippet

这是一个代码片段

package snippet;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;

public class TestDateFormat {

    public static void main(String[] args) throws ParseException {

        Date d = DateUtils.parseDate("23/10/2014T12:34:22", 
            new String[] {"yyyy/MM/dd'T'HH:mm:ss",
                "dd/MM/yyyy'T'HH:mm:ss"});

        System.out.println(d);
        //returns Tue Apr 05 12:34:22 CET 29 which is wrong
    }

}

采纳答案by Tobías

You should use DateUtils.parseDateStrictly:

你应该使用DateUtils.parseDateStrictly

DateUtils#parseDateStrictly

DateUtils#parseDateStrictly

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.

The parser parses strictly - it does not allow for dates such as "February 942, 1996".

通过尝试各种不同的解析器来解析表示日期的字符串。

解析将依次尝试每个解析模式。只有解析了整个输入字符串,解析才被认为是成功的。如果没有匹配的解析模式,则抛出 ParseException。

解析器会严格解析 - 它不允许使用诸如“February 942, 1996”之类的日期。

Internally, what it does is setting to falsethe lenientattribute of the DateFormatused: DateFormat.html#setLenient

在内部,它所做的是设置所使用falselenient属性DateFormatDateFormat.html#setLenient

Specify whether or not date/time parsing is to be lenient. With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format. With strict parsing, inputs must match this object's format.

指定日期/时间解析是否宽松。通过宽松解析,解析器可以使用试探法来解释与此对象格式不精确匹配的输入。使用严格解析,输入必须与此对象的格式匹配。

Example:

例子:

   public static void main(String[] args) throws ParseException {
      Date d = DateUtils.parseDateStrictly("23/10/2014T12:34:22", 
          new String[] {"yyyy/MM/dd'T'HH:mm:ss",
              "dd/MM/yyyy'T'HH:mm:ss"});

      System.out.println(d);
  }