在Java SDK 8中,日期和時間API是通過java.time
包提供的
import java.time.LocalDate;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
System.out.println("當前日期: " + currentDate);
LocalDate birthDate = LocalDate.of(2000, 1, 1);
System.out.println("出生日期: " + birthDate);
}
}
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime currentTime = LocalTime.now();
System.out.println("當前時間: " + currentTime);
LocalTime specificTime = LocalTime.of(14, 30, 0);
System.out.println("特定時間: " + specificTime);
}
}
LocalDate
和LocalTime
。import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("當前日期和時間: " + currentDateTime);
LocalDateTime specificDateTime = LocalDateTime.of(2025, 12, 31, 23, 59, 59);
System.out.println("特定日期和時間: " + specificDateTime);
}
}
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
System.out.println("當前帶時區(qū)的日期和時間: " + currentZonedDateTime);
}
}
import java.time.LocalDate;
import java.time.Period;
public class Main {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate birthDate = LocalDate.of(2000, 1, 1);
Period age = Period.between(birthDate, currentDate);
System.out.println("年齡: " + age.getYears() + " 歲");
}
}
import java.time.LocalTime;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
LocalTime startTime = LocalTime.now();
// 模擬一些操作
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime endTime = LocalTime.now();
Duration duration = Duration.between(startTime, endTime);
System.out.println("經(jīng)過的時間: " + duration.getSeconds() + " 秒");
}
}
這些類和方法可以幫助你根據(jù)需求處理日期和時間。更多詳細信息和用法,請參閱官方文檔。