2つの解決策:
- OffsetDateTime(Java 8に組み込まれています)
- joda(すべての強力な日付-サードパーティのライブラリ)
ここでは、OffsetDateTimeの方が明らかに優れたオプションですが、jodaがかなり前から非常に強力であることが証明されており、誰かがそれを使用することを好む場合は、以下のコードに両方のサンプルがあります。
両方のアプローチのコードサンプルを以下に示します。
public class Demo {
public static void jodaTimeStuff(String dateString, DateTimeZone dtz) {
System.out.println(StringUtils.leftPad(dateString, 29, " ") + "\t------->\t" + ISODateTimeFormat.dateTime().parseDateTime(dateString).toDateTime(dtz));
System.out.println(StringUtils.leftPad(dateString, 29, " ") + "\t------->\t" + OffsetDateTime.parse(dateString).toZonedDateTime());
}
public static void main(String[] args) throws Exception {
jodaTimeStuff("2010-03-01T08:00:00.000Z", DateTimeZone.UTC);
jodaTimeStuff("2010-03-01T08:00:00.000Z", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
jodaTimeStuff("2010-03-01T00:00:00.000-08:00", DateTimeZone.UTC);
jodaTimeStuff("2010-03-01T00:00:00.000-08:00", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
jodaTimeStuff("2010-03-01T00:00:00.000+05:30", DateTimeZone.UTC);
jodaTimeStuff("2010-03-01T00:00:00.000+05:30", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
jodaTimeStuff("2021-11-15T02:27:24.540288Z", DateTimeZone.UTC);
jodaTimeStuff("2021-11-15T02:27:24.540288Z", DateTimeZone.forTimeZone(TimeZone.getTimeZone("Asia/Kolkata")));
}
}
出力:
2010-03-01T08:00:00.000Z -------> 2010-03-01T08:00:00.000Z
2010-03-01T08:00:00.000Z -------> 2010-03-01T08:00Z
2010-03-01T08:00:00.000Z -------> 2010-03-01T13:30:00.000+05:30
2010-03-01T08:00:00.000Z -------> 2010-03-01T08:00Z
2010-03-01T00:00:00.000-08:00 -------> 2010-03-01T08:00:00.000Z
2010-03-01T00:00:00.000-08:00 -------> 2010-03-01T00:00-08:00
2010-03-01T00:00:00.000-08:00 -------> 2010-03-01T13:30:00.000+05:30
2010-03-01T00:00:00.000-08:00 -------> 2010-03-01T00:00-08:00
2010-03-01T00:00:00.000+05:30 -------> 2010-02-28T18:30:00.000Z
2010-03-01T00:00:00.000+05:30 -------> 2010-03-01T00:00+05:30
2010-03-01T00:00:00.000+05:30 -------> 2010-03-01T00:00:00.000+05:30
2010-03-01T00:00:00.000+05:30 -------> 2010-03-01T00:00+05:30
2021-11-15T02:27:24.540288Z -------> 2021-11-15T02:27:24.540Z
2021-11-15T02:27:24.540288Z -------> 2021-11-15T02:27:24.540288Z
2021-11-15T02:27:24.540288Z -------> 2021-11-15T07:57:24.540+05:30
2021-11-15T02:27:24.540288Z -------> 2021-11-15T02:27:24.540288Z
サンプルコードで使用されているいくつかの依存関係(1つはフォーマット用で、もう1つはjoda用です:
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.13</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8</version>
</dependency>
Dua me yaad rakhna(あなたの祈りの中で私を覚えておいてください)