当使用Java 8中的新日期/时间API时,你可以使用java.time
包中的类来处理日期和时间。以下是一些使用新的日期/时间API的示例代码:
java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("当前日期: " + currentDate);
// 获取当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("当前时间: " + currentTime);
// 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期和时间: " + currentDateTime);
// 使用自定义日期
LocalDate customDate = LocalDate.of(2024, Month.APRIL, 17);
System.out.println("自定义日期: " + customDate);
// 使用自定义时间
LocalTime customTime = LocalTime.of(15, 30, 45);
System.out.println("自定义时间: " + customTime);
// 使用自定义日期和时间
LocalDateTime customDateTime = LocalDateTime.of(2024, Month.APRIL, 17, 15, 30, 45);
System.out.println("自定义日期和时间: " + customDateTime);
// 格式化日期时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("格式化后的日期时间: " + formattedDateTime);
// 解析字符串为日期时间
String dateString = "2024-04-17";
LocalDate parsedDate = LocalDate.parse(dateString);
System.out.println("解析后的日期: " + parsedDate);
String timeString = "15:30:45";
LocalTime parsedTime = LocalTime.parse(timeString);
System.out.println("解析后的时间: " + parsedTime);
String dateTimeString = "2024-04-17T15:30:45";
LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString);
System.out.println("解析后的日期时间: " + parsedDateTime);
// 获取特定日期的年、月、日
LocalDate date = LocalDate.of(2024, Month.APRIL, 17);
int year = date.getYear();
Month month = date.getMonth();
int dayOfMonth = date.getDayOfMonth();
DayOfWeek dayOfWeek = date.getDayOfWeek();
System.out.println("Year: " + year);
System.out.println("Month: " + month);
System.out.println("Day of Month: " + dayOfMonth);
System.out.println("Day of Week: " + dayOfWeek);
// 判断是否为闰年
boolean isLeapYear = date.isLeapYear();
System.out.println("Is leap year? " + isLeapYear);
// 日期加减操作
LocalDate futureDate = date.plusDays(7); // 增加7天
LocalDate pastDate = date.minusWeeks(3); // 减少3周
System.out.println("Future Date: " + futureDate);
System.out.println("Past Date: " + pastDate);
// 比较日期
LocalDate otherDate = LocalDate.of(2024, Month.APRIL, 20);
boolean isBefore = date.isBefore(otherDate);
boolean isAfter = date.isAfter(otherDate);
boolean isEqual = date.equals(otherDate);
System.out.println("Is before? " + isBefore);
System.out.println("Is after? " + isAfter);
System.out.println("Is equal? " + isEqual);
// 计算两个日期之间的天数差
long daysBetween = ChronoUnit.DAYS.between(date, otherDate);
System.out.println("Days between dates: " + daysBetween);
}
}