Javaの時間関数の使い方を教えてください。
Javaでは、時間と日付を操作するためにjava.util.Dateやjava.util.Calendarクラス、そしてJava 8で導入されたjava.timeパッケージを使用することができます。
以下は一般的な時間関数の使用例です。
- 現在の日付と時間を取得する:
import java.util.Date;
Date currentDate = new Date();
System.out.println(currentDate);
- 日付のフォーマット化:
import java.text.SimpleDateFormat;
import java.util.Date;
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = dateFormat.format(currentDate);
System.out.println(formattedDate);
- 特定の日付と時間を取得する:
import java.util.Calendar;
Calendar calendar = Calendar.getInstance();
calendar.set(2022, Calendar.OCTOBER, 1);
Date specificDate = calendar.getTime();
System.out.println(specificDate);
- 日付の差を計算する:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate date1 = LocalDate.of(2022, 1, 1);
LocalDate date2 = LocalDate.of(2022, 12, 31);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
System.out.println(daysBetween);
- 日付と時間の形式を設定する(Java 8以降):
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println(formattedDateTime);
Java 8以前のjava.util.Dateやjava.util.Calendarクラスは、日付や時間の処理において機能が制限されていますが、java.timeパッケージはより豊富で使いやすいAPIを提供しています。