SimpleDateFormat中的可选部分

时间:2011-05-05 11:58:53

标签: java datetime localization simpledateformat

我正在阅读可能有或没有时区调整的日期字符串:yyyyMMddHHmmsszyyyyMMddHHmmss。当一个字符串缺少一个区域时,我将其视为GMT。我没有看到在SimpleDateFormat中创建可选部分的任何方法,但也许我错过了一些东西。有没有办法用SimpleDateFormat执行此操作,还是应该编写一个新的具体DateFormat来处理此问题?

7 个答案:

答案 0 :(得分:46)

JSR-310已经与Java 8一起提供,它为解析时间值提供了增强的支持,其中组件现在可以是可选的。您不仅可以将区域设为可选区域,还可以使时间组件可选,并为给定字符串返回正确的时间单位。

考虑以下测试用例。

public class DateFormatTest {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
            "yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]");

    private TemporalAccessor parse(String v) {
        return formatter.parseBest(v,
                                   ZonedDateTime::from,
                                   LocalDateTime::from,
                                   LocalDate::from);
    }

    @Test public void testDateTime1() {
        assertEquals(LocalDateTime.of(2014, 9, 23, 14, 20, 59),
                     parse("2014-09-23T14:20:59"));
    }

    @Test public void testDateTime2() {
        assertEquals(LocalDateTime.of(2014, 9, 23, 14, 20),
                     parse("2014-09-23 14:20"));
    }

    @Test public void testDateOnly() {
        assertEquals(LocalDate.of(2014, 9, 23), parse("2014-09-23"));
    }

    @Test public void testZonedDateTime() {
        assertEquals(ZonedDateTime.of(2014, 9, 23, 14, 20, 59, 0,
                                      ZoneOffset.ofHoursMinutes(10, 30)),
                     parse("2014-09-23T14:20:59+10:30"));
    }

}

此处"yyyy-MM-dd[[ ]['T']HH:mm[:ss][XXX]]" private final DateTimeFormatter formatter = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DateTimeFormatter.ISO_LOCAL_DATE) .optionalStart() .optionalStart() .appendLiteral(' ') .optionalEnd() .optionalStart() .appendLiteral('T') .optionalEnd() .appendOptional(DateTimeFormatter.ISO_TIME) .toFormatter(); 模式允许方括号内的选项也可以嵌套。模式也可以从DateTimeFormatter构建,上面的模式在这里演示:

yyyy-MM-dd[[' ']['T']HH:mm[':'ss[.SSS]]].

这将转换为如下所示的表达式:

2018-03-08 T11:12

可选值可以嵌套,如果仍然打开,也会在结尾处自动关闭。但请注意,无法在可选部件上提供异或,因此上述格式实际上会很好地解析以下值:

{{1}}

请注意,我们可以将现有格式化程序重用为当前格式的一部分。

答案 1 :(得分:32)

我知道这是一个老帖子,但只是为了记录......

Apache DateUtils类可以帮助您。

String[] acceptedFormats = {"dd/MM/yyyy","dd/MM/yyyy HH:mm","dd/MM/yyyy HH:mm:ss"};
Date date1 = DateUtils.parseDate("12/07/2012", acceptedFormats);
Date date2 = DateUtils.parseDate("12/07/2012 23:59:59", acceptedFormats);

链接到Maven存储库中的 Apache Commons Lang 库,您可能想查看最新版本:
http://mvnrepository.com/artifact/org.apache.commons/commons-lang3

Maven v3.4

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.4</version>
</dependency>

Gradle v3.4

'org.apache.commons:commons-lang3:3.4'

答案 2 :(得分:21)

我会创建两个SimpleDateFormat,一个带有时区,一个没有。您可以查看String的长度以确定要使用的字符串。


听起来你需要一个委托给两个不同SDF的DateFormat。

DateFormat df = new DateFormat() {
    static final String FORMAT1 = "yyyyMMddHHmmss";
    static final String FORMAT2 = "yyyyMMddHHmmssz";
    final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
    final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);
    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
        if (source.length() - pos.getIndex() == FORMAT1.length())
            return sdf1.parse(source, pos);
        return sdf2.parse(source, pos);
    }
};
System.out.println(df.parse("20110102030405"));
System.out.println(df.parse("20110102030405PST"));

答案 3 :(得分:3)

如果您可以使用Joda Datetime,它支持格式化程序中的可选部分,例如“yyyy-MM-dd [hh:mm:ss]”

private DateTimeFormatter fmt = new DateTimeFormatterBuilder()
.append(DateTimeFormat.forPattern("yyyy-MM-dd"))                                            
.appendOptional(
    new DateTimeFormatterBuilder()
    .appendLiteral(' ')
    .append(DateTimeFormat.forPattern("HH:mm:ss"))
    .toParser()
.toFormatter();

答案 4 :(得分:2)

我会使用DateFormat操作遍历潜在try-catch对象列表,以打破第一个成功解析的循环。

答案 5 :(得分:0)

您可以创建两个不同的SimpleDateFormats

 public PWMDateTimeFormatter(String aPatternStr)
    {
        _formatter = DateTimeFormat.forPattern(aPatternStr);
    }



    public PWMDateTimeFormatter(String aPatternStr, TimeZone aZone)
    {
        _formatter =   DateTimeFormat.forPattern(aPatternStr).withZone(XXDateTime._getTimeZone(aZone));
    }

答案 6 :(得分:0)

我通过扩展SimpleDateFormat解决了类似的问题。下面粗略的实现,以显示我的解决方案的想法。它可能没有完全/优化。

public class MySimpleDateFormat extends SimpleDateFormat {
    private static final long serialVersionUID = 1L;
    private static String FORMAT = "        
    private static int FORMAT_LEN = "yyyyMMddHHmmss".length();
    private static String TZ_ID = "GMT";

    public MySimpleDateFormat() {
            this(TimeZone.getTimeZone(TZ_ID));
    }

    public MySimpleDateFormat(TimeZone tz) {
            super(FORMAT);
            setTimeZone(tz);
    }

    @Override
    public Date parse(String source, ParsePosition pos) {
            // TODO: args validation
            int offset = pos.getIndex() + FORMAT_LEN;
            Date result;
            if (offset < source.length()) {
                    // there maybe is a timezone
                    result = super.parse(source, pos);
                    if (result != null) {
                            return result;
                    }
                    if (pos.getErrorIndex() >= offset) {
                            // there isn't a TZ after all
                            String part0 = source.substring(0, offset);
                            String part1 = source.substring(offset);
                            ParsePosition anotherPos = new ParsePosition(pos.getIndex());
                            result = super.parse(part0 + TZ_ID + part1, anotherPos);
                            if(result == null) {
                                    pos.setErrorIndex(anotherPos.getErrorIndex());
                            } else {
                                    // check SimpleDateFormat#parse javadoc to implement correctly the pos updates
                                    pos.setErrorIndex(-1);
                                    pos.setIndex(offset);
                            }
                            return result;
                    }
                    // there's something wrong with the first FORMAT_LEN chars
                    return null;
            }
            result = super.parse(source + TZ_ID, pos);
            if(result != null) {
                    pos.setIndex(pos.getIndex() - TZ_ID.length());
            }
            return result;
    }

    public static void main(String [] args) {
            ParsePosition pos = new ParsePosition(0);
            MySimpleDateFormat mySdf = new MySimpleDateFormat();
            System.out.println(mySdf.parse("20120622131415", pos) + " -- " + pos);
            pos = new ParsePosition(0);
            System.out.println(mySdf.parse("20120622131415GMT", pos) + " -- " + pos);
            pos = new ParsePosition(0);
            System.out.println(mySdf.parse("20120622131415xxx", pos) + " -- " + pos);
            pos = new ParsePosition(0);
            System.out.println(mySdf.parse("20120x22131415xxx", pos) + " -- " + pos);
    }
}

要点是你需要检查输入字符串并以某种方式“猜测”缺少TZ字段,如果是,则添加它然后让SimpleDateFormat#parse(String, ParsePosition)完成其余的工作。上面的实现不是根据SimpleDateFormat#parse(String, ParsePosition)

中javadoc中的契约更新ParsePosition

该类有一个默认的ctor,因为只允许一种格式。

方法MySimpleDateFormat#parse(String, ParsePosition)SimpleDateFormat#parse(String)调用,因此足以涵盖这两种情况。

运行main()这是输出(如预期的那样)

Fri Jun 22 14:14:15 BST 2012 -- java.text.ParsePosition[index=14,errorIndex=-1]
Fri Jun 22 14:14:15 BST 2012 -- java.text.ParsePosition[index=17,errorIndex=-1]
Fri Jun 22 14:14:15 BST 2012 -- java.text.ParsePosition[index=14,errorIndex=-1]
null -- java.text.ParsePosition[index=0,errorIndex=5]