在Java中处理日期和时间,可以使用java.util.Date
、java.time.LocalDate
、java.time.LocalDateTime
等类。以下是一些常见的日期操作示例:
获取当前日期和时间:
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期和时间: " + now);
}
}
日期的格式化和解析:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
System.out.println("格式化日期: " + formattedDate);
LocalDateTime parsedDate = LocalDateTime.parse(formattedDate, formatter);
System.out.println("解析日期: " + parsedDate);
}
}
日期的加减操作:
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime addedDate = now.plusDays(5); // 加5天
LocalDateTime subtractedDate = now.minus(5, ChronoUnit.DAYS); // 减5天
System.out.println("加5天后的日期: " + addedDate);
System.out.println("减5天后的日期: " + subtractedDate);
}
}