【问题标题】:Joda time: Invalid format乔达时间:格式无效
【发布时间】:2014-11-17 10:53:25
【问题描述】:

我正在使用 Joda API 来格式化当前时间(结果必须是格式化为“yyyy-MM-dd HH:mm:ss”的字符串)。下面我提供我的代码和错误消息:

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = new DateTime();
String datetime = dtf.parseDateTime(dt.toString()).toString();

错误信息:

线程“AWT-EventQueue-0”中的异常 java.lang.IllegalArgumentException:无效格式: “2014-11-17T11:47:29.229+01:00”在“T11:47:29.229+01:00”处格式不正确 在 org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:899)

【问题讨论】:

    标签: java jodatime


    【解决方案1】:

    如果您想使用自定义格式转换为字符串,请执行

    DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
    DateTime dt = new DateTime();
    String datetime = dtf.print(dt);
    

    你目前在最后一行所做的是

    String defaultFormatted = dt.toString();
    // this is what contains the "T11:47:29.229+01:00" part
    
    DateTime dateTime = dtf.parseDateTime(defaultFormatted);
    // we're back at the beginning, this is equivalent to your original "dt"
    
    String defaultFormattedAgain = dateTime.toString();
    // and this is the same as the initial string with T11:..
    

    因此,您多次从字符串转换为 &,但从未使用 dtf 来实际格式化字符串的外观。

    【讨论】:

      【解决方案2】:

      默认的 DateTime 字符串表示需要不同的模式:

         DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'+01:00'");
      

      如果你想用你的模式格式化日期,你需要使用 print() 方法:

         DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
         DateTime dt = new DateTime();
         String datetime = dtf.print(dt);
      

      【讨论】:

      • 谢谢。但是如何生成当前日期和时间,然后将其格式化为“yyyy-MM-dd HH:mm:ss”?
      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      相关资源
      最近更新 更多