Java:LocalDateの使用方法

LocalDateはJava 8から導入された日付を取り扱うAPIです。

Java 7まではシステム日付(現在日付)を取得する場合、Date型やCalendar型で以下の方法を使用していましたが、これらの方法では時刻に注意する必要がありました。

Date date = new Date();
Calendar cal = Calendar.getInstance();

Java 8以降からは LocalDate, LocalDateTime 等を使用した日時操作が標準で可能となっています。

目次

LocalDateで現在日付を取得する方法

Javaソース

import java.time.LocalDate;

public class LocalDateSample {

	public static void main(String[] args) {
		final LocalDate nowDate = LocalDate.now();
		System.out.println("現在日:" + nowDate);
	}
}

コンソール

LocalDateで特定の日付を取得する方法

Javaソース

import java.time.LocalDate;

public class LocalDateSample {

	public static void main(String[] args) {
		LocalDate targetDate = LocalDate.of(2022, 12, 31);
		System.out.println("特定日付:" + targetDate);
	}
}

コンソール

LocalDate同士の比較

  • LocalDateではisAfter、isBefore、isEqualを使用して比較することが出来ます。 
    ソース説明
    boolean java.time.LocalDate.isAfter(ChronoLocalDate other)日付A > 日付Bの場合にtrueを返します。
    boolean java.time.LocalDate.isBefore(ChronoLocalDate other)日付A
    boolean java.time.LocalDate.isEqual(ChronoLocalDate other)日付A = 日付Bの場合にtrueを返します。
     

Javaソース

import java.time.LocalDate;

public class LocalDateSample {

	public static void main(String[] args) {
		LocalDate targetDate1 = LocalDate.of(2022, 12, 31);
		LocalDate targetDate2 = LocalDate.of(2022, 12, 30);
		System.out.println("targetDate1 > targetDate2 = " + targetDate1.isAfter(targetDate2));
		System.out.println("targetDate1 < targetDate2 = " + targetDate1.isBefore(targetDate2));
		System.out.println("targetDate1 = targetDate2 = " + targetDate1.isEqual(targetDate2));
	}
}

コンソール

 

0 0
Article Rating
申し込む
注目する
guest
0 コメント一覧
最も古い
最新 高評価
インラインフィードバック
すべてのコメントを見る
目次
0
あなたの考えが大好きです、コメントしてください。x