Java 8 新的时间api LocalDate/LocalDateTime

我正在参加「掘金·启航计划」

引言

在项目中,时间的使用必不可少,而java 8之前的时间api DateCalander等在使用上存在着很多问题,于是,jdk1.8引进了新的时间api -->LocalDateTime,很好解决了使用时间api所带来的问题。

先前槽点

  1. 使用Date或者Calendar表示时间很不方便
 Date date = new Date(2022,1,1);
 System.out.println(date);

会输出 Thu Feb 01 00:00:00 CST 3922

月份直接变成了Feb,而年份更是加上了1900

如果用calendar 指定月份,则需要注意月份从0开始,也就是表示1月要用0,或者使用提供的枚举

Calendar calendar = Calendar.getInstance();
calendar.set(2022, Calendar.AUGUST, 2);

但此时,Calendar年份的传值为2022,与年份一致,这样就导致了这两个时间api存在着不一致问题

  1. Calendar状态可变,在计算时需要创建一个新的Calendar

如calendar在add等操作之后,变成了一个新的Calendar,在下次比较时就可能会出现差错

 calendar.add(Calendar.DAY_OF_MONTH, 1);

3. SimpleDateTimeFormat是非线程安全的。

于是,发布了新的时间api--LocalDateTime很好解决了上面存在的问题

简介

LocalDate、 LocalTime、 LocalDateTime类的实例是不可变的对象, 分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。 它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。 顾名思义,LocalDate主要应用在日期,LocalTime主要应用在时间,而LocalDateTime则是时间和日期相结合。

方法概览

  • of: 静态工厂方法。

  • parse: 静态工厂方法,关注于解析。

  • get: 获取某些东西的值。

  • is: 检查某些东西的是否是true。

  • with: 不可变的setter等价物。

  • plus: 加一些量到某个对象。

  • minus: 从某个对象减去一些量。

  • to: 转换到另一个类型。

  • at: 把这个对象与另一个对象组合起来,例如: date.atTime(time)。

使用

  1. 获取LocalDateTime等对象

通过静态方法now() 获取

LocalDate now = LocalDate.now(); //获取当前的年月日  2023-05-07
System.out.println(now);

LocalTime now1 = LocalTime.now();//获取当前时间   13:05:46.609

System.out.println(now1);

LocalDateTime now2 = LocalDateTime.now();   //获取当前日期加时间  2023-05-07T13:05:46.609
System.out.println(now2);

通过of()指定年月日时分秒

LocalDate now = LocalDate.now(); //获取当前的年月日  2023-05-07
System.out.println(now);

LocalTime now1 = LocalTime.now();//获取当前时间   13:05:46.609

System.out.println(now1);

LocalDateTime now2 = LocalDateTime.now();   //获取当前日期加时间  2023-05-07T13:05:46.609
System.out.println(now2);

2. 获取对象相关参数,如年,月

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int dayOfYear = now.getDayOfYear();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();

3. 格式化日期方法 format()以及DateTimeFormatter的使用

LocalDate now = LocalDate.now();
//JDK1.8 格式化日期的类 DateTimeFormatter
//指定格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String dateStr = now.format(formatter);
System.out.println(dateStr); // 2023年05月07日

LocalDateTime localDateTime = LocalDateTime.now();
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
//把日期对象,格式化成日期字符串
String str = localDateTime.format(formatter2);
System.out.println(str); //2023年05月07日 13点57分53秒

4. 将LocalDateTime转换为LocalDate以及LocalTime

System.out.println(localDateTime.toLocalDate()); //2023-05-07
System.out.println(localDateTime.toLocalTime());// 13:57:53.061

5. 比较日期或时间


    // isAfter() 判断一个日期是否在指定日期之后
    // isBefore() 判断一个日期是否在指定日期之前
    // isEqual();
    // 判断两个日期是否相同
    // isLeapYear() 判断是否是闰年注意是LocalDate类中的方法
    LocalDateTime now = LocalDateTime.now();
    LocalDateTime of = LocalDateTime.of(2023, 5, 7,14,0,0);

    System.out.println("当前时间为"+now); //当前时间为2023-05-07T14:04:18.676

    boolean after = now.isAfter(of);
    System.out.println(after);  // true

    boolean before = of.isBefore(now);
    System.out.println(before); //true

    boolean equal = now.isEqual(of);
    System.out.println(equal); //false

    boolean equal1 = of.isEqual(of);
    System.out.println(equal1); //true


    //判断是不是闰年
    boolean leapYear = now.toLocalDate().isLeapYear();
    System.out.println(leapYear); //false

月份的比较会特殊一点

//      now.getMonth().compareTo() 月份之间比较 相同则为0
        Month month = LocalDate.now().getMonth();
        Month month1 = LocalDate.of(2023, 6, 1).getMonth();
        System.out.println(month.compareTo(month1));

6. 将一个日期字符串解析成日期对象

String dateStr = "2022-12-03";
LocalDate parse = LocalDate.parse(dateStr);
System.out.println(parse);


String dateStr2 = "2022年12月03日";
//按照指定格式来解析
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
LocalDate parse2 = LocalDate.parse(dateStr2, formatter); //
System.out.println(parse2);

System.out.println("======================");
String dateStr3 = "2021年10月05日 14点20分30秒";
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH点mm分ss秒");
LocalDateTime parse1 = LocalDateTime.parse(dateStr3, formatter2);
System.out.println(parse1);

7. 添加时间 plus

LocalDateTime ldt =LocalDateTime.now();
LocalDateTime localDateTime = ldt.plusYears(1);
LocalDateTime localDateTime1 = ldt.plusMonths(3);
LocalDateTime localDateTime2=ldt.plusHours(10);
LocalDateTime localDateTime2 = ldt.minusYears(8);

8. 计算时间间隔

  • Duration : 用于计算两个“时间”间隔的类

  • Period : 用于计算两个“日期”间隔的类


    //Duration:用于计算两个"时间”间隔的类
    Duration betweenNowAnd = Duration.between(preious, end);
    //long seconds = between.getSeconds(); //间隔的秒值
    long l = betweenNowAnd.toMillis();
    System.out.println("耗时:" + l + "毫秒");

    LocalDate birthday = LocalDate.of(2000, 3, 20);
    LocalDate nowday = LocalDate.now();
    //Period:用于计算两个“日期”间隔的类
    Period between = Period.between(birthday, nowday);
    int years = between.getYears();
    int months = between.getMonths();
    int days = between.getDays();
    System.out.println(years);
    System.out.println(months);
    System.out.println(days);
  1. 设定时区
//创建日期对象
LocalDateTime now = LocalDateTime.now();
//获取不同国家的日期时间根据各个地区的时区ID名创建对象
ZoneId timeID = ZoneId.of("Asia/Shanghai");
//根据时区ID获取带有时区的日期时间对象
ZonedDateTime time = now.atZone(timeID);
System.out.println(time);
//方式2 通过时区ID 获取日期对象
LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(now2);

小结

LocalDate/LocalDateTime都是不可变且线程安全的,位于java.time包中,可以为时区提供更好的支持,加上DateTimeFormatter之后日期的解析及格式化也更加得心应手。

猜你喜欢

转载自juejin.im/post/7235458133505015869