0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java8で、UTC日時のDate型を取得する

Last updated at Posted at 2019-03-19

はじめに

Java8で、Joda-time APIのconvertUTCToLocal()やconvertLocalToUTC()相当の処理です。
Date型はtimezoneに依存してしまうので、差を考慮してDate型にします。
データベースにUTC日時を保存するときに使いました。

Javaコード

Java7まで

org.joda.timeを使います。

    public static Date getUtcDate() {
        Date local = new Date();
        DateTimeZone zone = DateTimeZone.getDefault();
        long utc = zone.convertLocalToUTC(local.getTime(), false);
        return new Date(utc);
    }

Java8

java.timeを使います。

       public static Date getUtcDate() {
              ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
              ZonedDateTime local = now.withZoneSameLocal(ZoneId.systemDefault());
              return Date.from(local.toInstant());
       }

参考

https://stackoverflow.com/questions/45584220/utc-to-local-method-in-datetimezone-of-joda-time-to-java-8
https://docs.oracle.com/javase/jp/8/docs/api/java/time/ZonedDateTime.html

終わりに

Java8の日時は、すっきりしていいですね!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?