在Java中,可以使用java.util包中的類來處理日期和時間。以下是一些常用的類和方法:
LocalDate:表示不帶時間的日期。LocalTime:表示不帶日期的具體時間。LocalDateTime:表示帶日期和時間的對象。ZonedDateTime:表示帶時區信息的日期和時間。YearMonth:表示年月信息。Duration:表示時間間隔。Period:表示日期間隔。以下是一些常見的操作示例:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class DateTimeExample {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2021, 9, 1);
LocalTime time = LocalTime.of(14, 30);
LocalDateTime dateTime = LocalDateTime.of(date, time);
System.out.println("LocalDate: " + date);
System.out.println("LocalTime: " + time);
System.out.println("LocalDateTime: " + dateTime);
}
}
import java.time.Duration;
public class DateDifferenceExample {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2021, 9, 1);
LocalDate date2 = LocalDate.of(2021, 9, 10);
Duration duration = Duration.between(date1, date2);
System.out.println("Days between: " + duration.toDays());
}
}
import java.time.LocalDateTime;
import java.time.Duration;
public class AddIntervalExample {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2021, 9, 1, 14, 30);
Duration duration = Duration.ofHours(2).plusMinutes(30);
LocalDateTime newDateTime = dateTime.plus(duration);
System.out.println("New DateTime: " + newDateTime);
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormatDateTimeExample {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2021, 9, 1, 14, 30);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formattedDateTime = dateTime.format(formatter);
System.out.println("Formatted DateTime: " + formattedDateTime);
}
}
這些示例展示了如何使用java.util包中的類來處理日期和時間。在實際應用中,你可能需要根據具體需求選擇合適的類和方法。