简体   繁体   English

Java8解析给定字符串的日期或日期时间格式

[英]Java8 parse date or date time format for a given string

I have a file that can have a date modified value with the format of a date or date time. 我有一个文件可以具有日期修改值,具有日期或日期时间的格式。 I used to parse the value as: 我曾经将值解析为:

String t = "2012-01-05T21:21:52.834Z";
logger.info(ZonedDateTime.parse(t).toEpochSecond() * 1000);

Now, the string could also be 现在,字符串也可以

t = "2012-01-05";

which threw an error 哪个引起了错误

Exception in thread "main" java.time.format.DateTimeParseException: Text '2012-01-05' could not be parsed at index 10 at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source) 线程“main”中的异常java.time.format.DateTimeParseException:无法在java.time.format.DateTimeFormatter.parseResolved0(未知来源)的索引10处解析文本“2012-01-05”

If I do this string with ( Reference ) 如果我用这个字符串( 参考

LocalDate date = LocalDate.parse(t, DateTimeFormatter.ISO_DATE);
logger.info(date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond() * 1000);

This would work. 这会奏效。 However, as I have mentioned that string could be either of these types, how can I identify the format and then get the millis accordingly? 但是,正如我已经提到的那样,字符串可以是这些类型中的任何一种,我如何识别格式然后相应地得到毫秒?

A possible solution is to use optional pattern with default values. 可能的解决方案是使用具有默认值的可选模式。 Using a DateTimeFormatterBuilder , you can append the wanted pattern with the time part in an optional section, ie surrounded by [...] . 使用DateTimeFormatterBuilder ,您可以将所需模式与时间部分附加在可选部分中,即由[...]包围。 In the case where the fields are absent, we provide default values by setting them to 0. The OFFSET_SECONDS field to 0 represents no offset from UTC. 在没有字段的情况下,我们通过将它们设置为0来提供默认值OFFSET_SECONDS字段为0表示没有与UTC的偏移。

public static void main(String[] args) {
    String[] dates = { "2012-01-05T21:21:52.834Z", "2012-01-05" };

    DateTimeFormatter formatter = 
        new DateTimeFormatterBuilder().appendPattern("yyyy-MM-dd['T'HH:mm:ss.SSSz]")
                                      .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                                      .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                                      .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                                      .parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
                                      .parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
                                      .toFormatter();
    for (String date : dates) {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(date, formatter);
        System.out.println(zonedDateTime.toEpochSecond() * 1000);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM