【问题标题】:Joda DateTime Invalid formatJoda DateTime 格式无效
【发布时间】:2017-01-04 13:28:25
【问题描述】:

我正在尝试使用我的 DateTimeFormat 模式获取当前的 DateTime,但我遇到了异常...

//sets the current date
DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm").withLocale(locale);
DateTime now = dtf.parseDateTime(currentDate.toString());

我遇到了这个异常,我不明白是谁给出了格式错误的格式

java.lang.IllegalArgumentException: Invalid format: "2017-01-04T14:24:17.674+01:00" is malformed at "17-01-04T14:24:17.674+01:00"

【问题讨论】:

  • 您是尝试将日期格式化为字符串还是尝试将字符串解析为日期时间对象?
  • 应该是一个DateTime对象
  • 但是你开始DateTime - 为什么要把它转换成文本然后再转换回来?

标签: java datetime jodatime


【解决方案1】:

DateTime now = dtf.parseDateTime(currentDate.toString()); 这一行不正确,因为您尝试使用默认 toSring 格式解析日期。您必须解析格式与模式相同的字符串:

DateTime currentDate = new DateTime();
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd/MM/YYYY HH:mm").withLocale(locale);
String formatedDate = dtf.print(currentDate);
System.out.println(formatedDate);
DateTime now = dtf.parseDateTime(formatedDate);
System.out.println(now);

【讨论】:

    【解决方案2】:

    您使用了错误的格式来解析日期。如果您在使用toString 将其转换为字符串后打印出您尝试解析的日期,您会得到:

    2017-01-04T14:24:17.674+01:00
    

    此日期字符串不符合模式dd/MM/YYYY HH:mm。要再次解析将 currentDate 转换为 DateTime 对象的字符串,您必须使用以下模式:

    DateTimeFormatter dtf = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ss.SSSZ")
                                          .withLocale(locale);
    

    用这个DateTimeFormatter 解析会得到另一个与原始currentDate 表示同一时间的实例。

    有关DateTimeFormatter 及其解析选项的更多详细信息,请查看JavaDoc

    【讨论】:

      猜你喜欢
      • 2015-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多