Joda时间转换查询

时间:2014-07-10 11:03:54

标签: java jodatime

如何使用joda time API从“2014-06-16T07:00:00.000Z”转换为“16-JUN-14 07:00:00”?

以下代码抛出异常

java.lang.IllegalArgumentException: Illegal pattern component: T
    at org.joda.time.format.DateTimeFormat.parsePatternTo(DateTimeFormat.java:570)
    at org.joda.time.format.DateTimeFormat.createFormatterForPattern(DateTimeFormat.java:693)
    at org.joda.time.format.DateTimeFormat.forPattern(DateTimeFormat.java:181)
    at com.joda.JodaTimeTest.convertJodaTimezone(JodaTimeTest.java:59)
    at com.joda.JodaTimeTest.main(JodaTimeTest.java:50)

这是代码:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-ddTHH:mm:ssZ");
    DateTime dt = formatter.parseDateTime(dstDateTime.toString());

2 个答案:

答案 0 :(得分:4)

您需要将文字T括在单引号中。此外毫秒没有适当地图案化。您需要包含SSS毫秒。有关详细信息,请查看patterns here

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

更新:要将DateTime格式化为您选择的字符串表示形式,您需要执行此操作。

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTime dt = formatter.parseDateTime(dstDateTime.toString()); // You get a DateTime object

// Create a new formatter with the pattern you want
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("dd-MMM-yy HH:mm:ss");
String dateStringInYourFormat = formatter2.print(dt); // format the DateTime to that pattern
System.out.println(dateStringInYourFormat); // Prints 16-Jun-14 12:30:00 because of the TimeZone I'm in

您自己指定时区或将采用默认的系统时区。

答案 1 :(得分:1)

您需要更改

"yyyy-MM-ddTHH:mm:ssZ"

"yyyy-MM-dd'T'HH:mm:ss.SSS'Z"

现在

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z");
DateTime dt = formatter.parseDateTime("2014-06-16T07:00:00.000Z");
System.out.println(dt);

输出:

2014-06-16T07:00:00.000+05:30
相关问题