Jody time: date convert error

I am using Joda Time 2.3 to convert String to java.lang.Date.

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.3</version>
</dependency>

Here are some test codes:

System.out.println(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("1927-12-11 11:22:38"));
System.out.println(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("1927-12-11 11:22:38").toDate());

System.out.println(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("1937-12-11 11:22:38"));
System.out.println(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime("1937-12-11 11:22:38").toDate());

It works well under JDK 5 and JDK 7. But when using JDK 6, the result is:

1927-12-11T11:22:38.000+08:05:57
Sun Dec 11 11:22:33 CST 1927 // lose 5 second
1937-12-11T11:22:38.000+08:00
Sat Dec 11 11:22:38 CST 1937

You see that the first to convert to java.lang.Date lost 5 seconds, but the second is correct. The only difference is the year number, the first of which is 1927, and the second is 1937. All annual numbers below 1927 will lead to an incorrect one.

It must be something wrong with the jod. Can someone tell me how to avoid the error, or should I use SimpleDateFormatter.

Thank!

+4
source share
1 answer

Jon Skeets ? , , .

, tz ( , LMT - , ). IANA-tzdb 1970 .

EDIT:

"/" ( CST ) :

DateTimeZone tz = DateTimeZone.forID("Asia/Shanghai");

System.out.println(
  DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  .withZone(tz)
  .parseDateTime("1927-12-11 11:22:38"));
System.out.println(
  DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  .withZone(tz)
  .parseDateTime("1927-12-11 11:22:38")
  .toDate());

System.out.println(
  DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  .withZone(tz)
  .parseDateTime("1937-12-11 11:22:38"));
System.out.println(
  DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  .withZone(tz)
  .parseDateTime("1937-12-11 11:22:38")
  .toDate());

:

1927-12-11T11:22:38.000+08:05:52
Sun Dec 11 04:16:46 CET 1927 // toString() prints in standard time zone
1937-12-11T11:22:38.000+08:00
Sat Dec 11 04:22:38 CET 1937 // toString() prints in standard time zone

5 , (+08: 05: 52 +08: 05: 57 2013a tzdb - . this commit Paul Eggert). JDK- 5 6 change - SimpleDateFormat. . , SimpleDateFormat, . :

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setLenient(false);
df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
Date d = df.parse("1927-12-11 11:22:38");
System.out.println(d);
long offset = TimeZone.getTimeZone("Asia/Shanghai").getOffset(d.getTime()) / 1000;
System.out.println(offset);
int offsetHours = (int) (offset / 3600);
long minutes = (offset % 3600);
System.out.println(offsetHours + ":0" + minutes / 60 + ":" + (minutes % 60));

, tz 08:05:52 , java.util.Date.toString() - output ( CST ). , JodaTime, JDK JodaTime tzdb.

+5

Source: https://habr.com/ru/post/1533668/


All Articles