首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >java中的日期格式化程序

java中的日期格式化程序
EN

Stack Overflow用户
提问于 2018-09-14 21:23:54
回答 2查看 6K关注 0票数 2

我使用下面的代码来格式化毫秒解析日期字符串。它适用于2018-09-14T13:05:21.329Z,但不适用于2018-09-14T13:05:21.3Z。有没有人能建议一下原因以及如何纠正?

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
    Date parsedDate = formatter.parse(date);
    String destDate = sdfDestination.format(parsedDate);
    return destDate;
} catch (java.text.ParseException parseException) {
    logger.error("Parse Exception occured while converting publication time to date "
            + "format 'yyyy-MM-dd HH:mm:ss'", parseException);
}

我得到以下异常:

java.text.ParseException: Unparseable date: "2018-09-14T13:05:21.3Z"
    at java.text.DateFormat.parse(Unknown Source) ~[na:1.8.0_181]
    at com.noordpool.api.implementation.utility.Utility.parseDate(Utility.java:136) [classes/:na]
    at com.noordpool.api.implementation.utility.Utility.parseMessage(Utility.java:77) [classes/:na]
EN

回答 2

Stack Overflow用户

发布于 2018-09-14 21:35:10

我能看到的唯一可能的问题是,您错误地传递了毫秒数,并且程序不知道如何处理它。

因此,格式化程序的最后一部分用毫秒表示,时区表示为.SSSX

但它如何评估3Z对此的输入?我的意思是,你是说它是300时区Z,还是说它是003时区Z,或者更糟糕的是,试着把它解析成3Z,希望你能看到你不能把'3Z‘变成一个数字。

为了纠正这个问题,我会验证你的输入'date‘,并确保毫秒部分总是3位数的长度,这消除了歧义,程序总是知道你的意思是'300毫秒,时区Z’。

票数 1
EN

Stack Overflow用户

发布于 2018-09-14 21:44:45

在java 8中存在一个问题,即您使用格式化程序指定的字符数应该是完全匹配的(文档中没有指定)。您可以使用三种不同的格式,并使用嵌套异常,如下所示:

DateFormat format1 = new SimpleDateFormat("y-M-d'T'H:m:s.SX");
DateFormat format2 = new SimpleDateFormat("y-M-d'T'H:m:s.SSX");
DateFormat format3 = new SimpleDateFormat("y-M-d'T'H:m:s.SSSX");
Date parsedDate;

try {
    // Parsing for the case - 2018-09-14T13:05:21.3Z 
    parsedDate  = format1.parse(date); 
} catch (ParseException e1) {

    try {
         // Parsing for the case - 2018-09-14T13:05:21.32Z 
         parsedDate = format2.parse(date); 
    } catch (ParseException e2) {

          try {
              // Parsing for the case - 2018-09-14T13:05:21.329Z 
              parsedDate = format3.parse(date);
          } catch (ParseException e2) {
             //The input date format is wrong
             logger.error("Wrong format for date - " + date);      
          }

    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52332995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档