猿来绘Java-39-JDK8的新日期时间类

从JDK 1.0开始就有了java.util.Date类,它的大多数方法在JDK 1.1引入Calendar类之后被弃用,而Calendar并不比Date好多少。

它们都面临的问题是:

可变性:日期和时间这样的类应该是不可变的

偏移性: Date中的年份是从1900开始的,而月份都从0开始。偏移量没有统一,容易出错,难记忆。

格式化:格式化只对Date有用, Calendar则不行。

它们也不是线程安全的

不能处理闰秒

Java 8中引入的java.time API 已经纠正了过去的缺陷,将来很长一段时间内它都会为我们服务。

Java 8 吸收了 Joda-Time 的精华(JDK8之前的需要自己手动引入jar包),如果你使用的是JDK8之前的版本,可以使用Joda-Time中的时间类。

新的 java.time 中包含了所有关于本地日期(LocalDate)、本地时间(LocalTime)、本地日期时间(LocalDateTime)、时区(ZonedDateTime)和持续时间(Duration)的类。历史悠久的 Date 类新增了 toInstant() 方法,用于把 Date 转换成新的表示形式。这些新增的本地化时间日期 API 大大简化了日期时间和本地化的管理。

@Test
public void test3(){
    //now():获取当前的日期、时间、日期+时间
    LocalDate localDate = LocalDate.now();
    LocalTime localTime = LocalTime.now();
    LocalDateTime localDateTime = LocalDateTime.now();

    System.out.println(localDate);
    System.out.println(localTime);
    System.out.println(localDateTime);

    //of():设置指定的年、月、日、时、分、秒。没有偏移量
    LocalDateTime localDateTime1 = LocalDateTime.of(2025, 1, 11, 22, 12, 43);
    System.out.println(localDateTime1);


    //getXxx():获取相关的属性
    System.out.println(localDateTime.getDayOfMonth());
    System.out.println(localDateTime.getDayOfWeek());
    System.out.println(localDateTime.getMonth());
    System.out.println(localDateTime.getMonthValue());
    System.out.println(localDateTime.getMinute());

    //体现不可变性,设置时会产生新的对象
    //withXxx():设置相关的属性
    LocalDate localDate1 = localDate.withDayOfMonth(22);
    System.out.println(localDate);
    System.out.println(localDate1);


    LocalDateTime localDateTime2 = localDateTime.withHour(4);
    System.out.println(localDateTime);
    System.out.println(localDateTime2);

    //不可变性
    LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
    System.out.println(localDateTime);
    System.out.println(localDateTime3);

    LocalDateTime localDateTime4 = localDateTime.minusDays(6);
    System.out.println(localDateTime);
    System.out.println(localDateTime4);
}

猜你喜欢

转载自blog.csdn.net/asdfjklingok/article/details/118080174