在Java中,处理日期和时间的类主要集中在 java.time
包中,这是自Java 8引入的新的日期和时间API。以下是一些常用的类及其方法.
1. LocalDate
LocalDate
表示不带时区的日期。
常用方法示例:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class LocalDateExample {
public static void main(String[] args) {
// 获取当前日期
LocalDate today = LocalDate.now();
System.out.println("Today's date: " + today);
// 创建特定日期
LocalDate specificDate = LocalDate.of(2023, 10, 1);
System.out.println("Specific date: " + specificDate);
// 格式化日期
String formattedDate = today.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println("Formatted date: " + formattedDate);
// 获取年、月、日
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day);
// 添加天数
LocalDate futureDate = today.plusDays(10);
System.out.println("Date after 10 days: " + futureDate);
// 减少天数
LocalDate pastDate = today.minusDays(10);
System.out.println("Date before 10 days: " + pastDate);
}
}
2. LocalTime
LocalTime
表示不带时区的时间。
常用方法示例:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class LocalTimeExample {
public static void main(String[] args) {
// 获取当前时间
LocalTime now = LocalTime.now();
System.out.println("Current time: " + now);
// 创建特定时间
LocalTime specificTime = LocalTime.of(14, 30, 0);
System.out.println("Specific time: " + specificTime);
// 格式化时间
String formattedTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println("Formatted time: " + formattedTime);
// 获取小时、分钟、秒
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.println("Hour: " + hour + ", Minute: " + minute + ", Second: