LoginSignup
0
1

More than 3 years have passed since last update.

【Java】Time ( 日付操作 )

Last updated at Posted at 2020-11-29

Timeクラス

【説明】

DateクラスとCalendarクラスの問題を解決するために新しく出来たクラスです。
TimeDateクラスとCalendarクラスの両方の特徴があり、

  • 日付データ保持
  • 日付操作

これら両方とも Timeクラス1つで賄うことが出来てしまいます。

Timeクラスには、

  • LocalDate
  • Localtimeのインスタンスを持つLocalDateTime
  • LocalDateTimeに加え
  • オフセット(標準時との時差)を含むOffsetDateTime
  • OffsetDateTimeに加え
  • タイムゾーンを含むZonedDateTimeがあります。
クラス名 機能と役割
Instant 世界における、ある「瞬間」の時刻を、ナノ秒単位で厳密に指し示し、保持する
ZoneDateTime 世界における、ある「瞬間」の時刻を、ナノ秒単位で厳密に指し示し、保持する 2020-11-30T23:30:59.999+09:00[Asia/Tokyo]
LocalDateTime 内部にLocalDateとLocalTimeのインスタンスを持っている。
日常的に使われる「曖昧な日時」を保持する
タイムゾーンのない日時
2020-11-30T23:30:59.999
Duration 2つの異なる時刻や日付の期間を保持する
Period 2つの異なる時刻や日付の期間を保持する
OffsetDateTime オフセット付きの日時。 2020-11-30T23:30:59.999+09:00

また、月の値の対応もCalendarクラスと異なっており、月の値が1場合 1月 として出力されます。

【使用場面】

時間 」を扱う場面全般で使用できます。

※ 現場の中には、「伝統的なDateCalendarを使用するので、Time Apiは積極活用しない」という場所もあるので、実務では現場のルールに従うこと。

【サンプルコード】


// LocalDateTime のインポート
import java.time.LocalDateTime;
// OffsetDateTime のインポート
import java.time.OffsetDateTime;
// ZonedDateTime のインポート
import java.time.ZonedDateTime;

public class AboutTimeMain {

    public static void main(String[] args) {
        // LocalDateTime で現在時刻を取得
        LocalDateTime ldtNow = LocalDateTime.now();
        // OffsetDateTime で現在時刻を取得
        OffsetDateTime odtNow = OffsetDateTime.now();
        // ZonedDateTime で現在時刻を取得
        ZonedDateTime zdtNow = ZonedDateTime.now();

        // それぞれのTimeクラスを出力する。
        System.out.println("LocalDateTime は" + ldtNow.toString());
        System.out.println("OffsetDateTime は" + odtNow.toString());
        System.out.println("ZonedDateTime は" + zdtNow.toString());
    }
}

【実行結果】

LocalDateTime は2020-11-29T16:48:21.834565
OffsetDateTime は2020-11-29T16:48:21.835357+09:00
ZonedDateTime は2020-11-29T16:48:21.836312+09:00[Asia/Tokyo]

【サンプルコード】

TimeクラスはDateクラスやCalendarクラスと異なり、「直接値を変更することができない」ため、「 日時などの値を変更する場合はインスタンスを生成しなおす」 必要があります。

// LocalDateTime のインポート
import java.time.LocalDateTime;

public class AboutTimeMain {

    public static void main(String[] args) {
        // LocalDateTime で現在時刻を取得
        LocalDateTime ldtNow = LocalDateTime.now();
        System.out.println(ldtNow.getMonthValue() + "月です。");

        // インスタンス の再生成
        ldtNow = ldtNow.withMonth(5);
        System.out.println(ldtNow.getMonthValue() + "月に変更しました。");
    }
}

【実行結果】

11月です。
5月に変更しました。
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