java 8以上 时间类处理

126 阅读2分钟

在Java 8及以上版本中,我们可以使用新的日期和时间API,这些API在java.time包中。这个新的API比旧的java.util.Date和java.util.Calendar更加强大且易于使用。以下是一些主要的类:

  1. LocalDate:这个类表示一个日期(年/月/日)。它是不可变且线程安全的。

    示例:

    LocalDate date = LocalDate.now();
    System.out.println(date);  // 打印当前日期
    
  2. LocalTime:这个类表示一天中的时间(小时/分钟/秒)。它也是不可变且线程安全的。

    示例:

    LocalTime time = LocalTime.now();
    System.out.println(time);  // 打印当前时间
    
  3. LocalDateTime:这个类表示日期和时间。它是LocalDate和LocalTime的组合。

    示例:

    LocalDateTime dateTime = LocalDateTime.now();
    System.out.println(dateTime);  // 打印当前日期和时间
    
  4. Period:这个类表示两个日期之间的时间段。

    示例:

    LocalDate date1 = LocalDate.of(2020, 1, 1);
    LocalDate date2 = LocalDate.of(2023, 1, 1);
    Period period = Period.between(date1, date2);
    System.out.println(period);  // 打印两个日期之间的时间段
    
  5. Duration:这个类表示两个时间之间的时间段。

    示例:

    LocalTime time1 = LocalTime.of(10, 0);
    LocalTime time2 = LocalTime.of(11, 0);
    Duration duration = Duration.between(time1, time2);
    System.out.println(duration);  // 打印两个时间之间的时间段
    

这些类都提供了丰富的方法来处理日期和时间,例如添加或减少年份、月份、天数、小时、分钟和秒等。

在Java 8及以上版本中,我们可以使用DateTimeFormatter类来格式化或解析日期和时间。以下是一些示例:

  1. 格式化LocalTime:
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String formattedTime = time.format(formatter);
        System.out.println(formattedTime);  // 打印格式化后的时间
    }
}
  1. 格式化LocalDateTime:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = dateTime.format(formatter);
        System.out.println(formattedDateTime);  // 打印格式化后的日期和时间
    }
}

在这些示例中,我们使用了DateTimeFormatter的ofPattern方法来创建一个格式化器,然后使用LocalTime或LocalDateTime的format方法来格式化日期和时间。这些格式化器可以用各种模式,例如"yyyy-MM-dd"表示年-月-日,"HH:mm:ss"表示时:分:秒。