Java JDK8新日期时间API(LocalDate、LocalTime、LocalDateTime类和比较器说明)

Java 8 引入了全新的日期时间API,解决了旧API的可变性、偏移性、格式化和线程安全问题。新API包含LocalDate、LocalTime和LocalDateTime类,它们是不可变对象,分别表示日期、时间及日期时间。LocalDate适用于存储生日等日期,LocalTime仅表示时间,LocalDateTime是最常用的类之一。此外,DateTimeFormatter提供日期时间的格式化和解析,支持ISO标准和自定义格式。Comparable接口用于对象的自然排序,Comparator接口则用于定制排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java JDK8新日期时间API(LocalDate、LocalTime、LocalDateTime类)

  • JDK8之前日期时间API存在的问题:

    • 可变性:一般需要的日期和时间这样的类应该是不可变的
    • 偏移性:Date中的年份是从1900年开始的,而月份都是从0开始的
    package www.bh.c.datanewtest;
    import java.util.Date;
    
    public class Test01 {
        public static void main(String[] args) {
            Date date = new Date(2020,11,13);
            System.out.println(date);//Mon Dec 13 00:00:00 CST 3920
        }
    }
    
    package www.bh.c.datanewtest;
    
    import java.util.Date;
    
    public class Test01 {
        public static void main(String[] args) {
            Date date = new Date(2020,11,13);
            System.out.println(date);//Mon Dec 13 00:00:00 CST 3920
            Date date1 = new Date(2020 - 1900, 11 - 1, 13);
            System.out.println(date1);//Fri Nov 13 00:00:00 CST 2020
        }
    }
    
    • 格式化:格式化只对Date有用,Calendar则不行
    • 线程不安全
  • 新时间日期API,新的java.time中包含了所有关于本地日期(LocalDate)、(LocalTime)、本地日期时间(LocalDateTime)、时区(ZoneedDateTime)、持续时间(Duration)的类

  • 新时间日期API

    • java.time - 包含值对象的基础包
    • java.time.chrono - 提供对不同的日历系统的访问
    • java.time.format - 格式化和解析时间和日期
    • java.time.temporal - 包括底层框架和扩展特性
    • java.time.zone - 包含时区支持的类
  • LocalDate、LocalTime、LocalDateTime类

    • 这三个是比较重要的类,实例是不可变的对象,分别表示使用ISO-8601日历系统的日期、时间、日期和时间
    • LocalDate代表IOS格式(yyyy-MM-dd的日期,可以存储生日、纪念日等日期
    • LocalTime表示一个时间,而不是日期
    • LocalDateTime表示日期和时间,最常用的类之一
    • LocalDate、LocalTime、LocalDateTime类的使用
package www.bh.c.datanewtest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Test02 {
    public static void main(String[] args) {
        //now():获取当前的日期、时间、日期时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDate);//2020-11-13
        System.out.println(localTime);//10:30:32.669231100
        System.out.println(localDateTime);//2020-11-13T10:30:32.669231100
    }
}
package www.bh.c.datanewtest;
import java.time.LocalDateTime;

public class Test02 {
    public static void main(String[] args) {
    //of():设置指定的年、月、日、时、分、秒。没有偏移量
        LocalDateTime localDateTime = LocalDateTime.of(2020,11,13,10,31);
        System.out.println(localDateTime);//2020-11-13T10:31
    }
}
package www.bh.c.datanewtest;
import java.time.LocalDateTime;

public class Test02 {
    public static void main(String[] args) {
//getxxx():获取相关的属性
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime.getDayOfMonth());//13
        System.out.println(localDateTime.getDayOfWeek());//FRIDAY
        System.out.println(localDateTime.getDayOfYear());//318
        System.out.println(localDateTime.getHour());//10
        System.out.println(localDateTime.getMinute());//40
        System.out.println(localDateTime.getNano());//607710300
    }
}
package www.bh.c.datanewtest;
import java.time.LocalDate;
import java.time.LocalDateTime;
//withXXX():设置相关的属性,体现不可变性
public class Test02 {
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.now();
        LocalDate localDate1 = localDate.withYear(2030);
        System.out.println(localDate);//2020-11-13
        System.out.println(localDate1);//2030-11-13

        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime localDateTime1 = localDateTime.withHour(2);
        System.out.println(localDateTime);//2020-11-13T10:49:17.387000800
        System.out.println(localDateTime1);//2020-11-13T02:49:17.387000800
    }
}
package www.bh.c.datanewtest;
import java.time.LocalDateTime;

public class Test02 {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        //plus:加上自定义日期时间
        LocalDateTime localDateTime = now.plusHours(3);
        System.out.println(now);//2020-11-13T14:57:24.841595800
        System.out.println(localDateTime);//2020-11-13T17:57:24.841595800
        //minus:减去自定义日期时间
        LocalDateTime localDateTime1 = now.minusDays(3);
        System.out.println(now);//2020-11-13T14:57:24.841595800
        System.out.println(localDateTime1);//020-11-10T14:57:24.841595800
    }
}
  • Instant(瞬时)
    • 时间线上的一个时间点,用来记录事件时间戳
    • 在UNIX中,时间戳是以1970年开始,以秒为单位的;同样在Java中,也是以1970年开始,但以毫秒为单位
    • java.time包是基于纳秒计算的,所以instant的精度可以达到纳秒级
    • 1 s=1000毫秒=106微妙=109纳秒
    • Instan的使用
package www.bh.c.datanewtest;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Test03 {
    public static void main(String[] args) {
        //now():获取本初子午线对应的标准时间,因为时区的影响会存在时间的偏移量
        Instant now = Instant.now();
        System.out.println(now);//2020-11-13T07:16:20.512479600Z
        //添加时间的偏移量
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2020-11-13T15:17:37.963277300+08:00
        //toEpochMilli():获取自11970年1月1日0时0分0秒(UTC)开始的毫秒数
        long l = now.toEpochMilli();
        System.out.println(l);//1605251900924
        //toEpochMilli():通过给定的毫秒数,获取Instant实例
        Instant instant = Instant.ofEpochMilli(1605251900924L);
        System.out.println(instant);//2020-11-13T07:18:20.924Z
    }
}
  • 格式化与解析日期和时间

    • java.time.foemat.DateTimeFormatter类:提供了三种格式化方法

      • ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
      package www.bh.c.datanewtest;
      import java.time.LocalDateTime;
      import java.time.format.DateTimeFormatter;
      
      public class Test04 {
          public static void main(String[] args) {
              DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
              //格式化:日期-->字符串
              LocalDateTime now = LocalDateTime.now();
              String s = dtf.format(now);
              System.out.println(now);//2020-11-13T15:40:48.369543900
              System.out.println(s);//2020-11-13T15:40:48.3695439
               //解析:字符串-->日期
               TemporalAccessor parse = dtf.parse("2020-11-13T15:58:49.144269100");
              System.out.println(parse);//{},ISO resolved to 2020-11-13T15:58:49.144269100
          }
      }
      
      • 本地化相关的格式。如ofLocalizedDateTime(FormatStyle.LONG)
      package www.bh.c.datanewtest;
      
      import java.time.LocalDateTime;
      import java.time.format.DateTimeFormatter;
      import java.time.format.FormatStyle;
      
      public class Test05 {
          public static void main(String[] args) {
              DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
              //格式化
              String format = dtf.format(LocalDateTime.now());
              System.out.println(dtf);//Localized(MEDIUM,MEDIUM)
              System.out.println(format);//2020年11月13日 下午4:14:37
          }
      }
      
      package www.bh.c.datanewtest;
      import java.time.LocalTime;
      import java.time.format.DateTimeFormatter;
      import java.time.format.FormatStyle;
      
      public class Test05 {
          public static void main(String[] args) {
              DateTimeFormatter dtf = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
              String format = dtf.format(LocalTime.now());
              System.out.println(format);//下午4:17
          }
      }
      
      • 自定义的格式:如:ofPatter(“yyyy-MM-dd hh-mm-ss E”)
      package www.bh.c.datanewtest;
      import java.time.LocalDateTime;
      import java.time.format.DateTimeFormatter;
      import java.time.temporal.TemporalAccessor;
      
      public class Test06 {
          public static void main(String[] args) {
              DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
              //格式化
              String format = dateTimeFormatter.format(LocalDateTime.now());
              System.out.println(format);//2020-11-13 04:21:16
             //解析  
              TemporalAccessor parse = dateTimeFormatter.parse("2020-12-12 04:20:41");
              System.out.println(parse);//{MicroOfSecond=0, SecondOfMinute=41, NanoOfSecond=0, MinuteOfHour=20, MilliOfSecond=0, HourOfAmPm=4},ISO resolved to 2020-12-12
          }
      }
      

    Java比较器

    • Java中的对象,正常情况下,只能进行比较:==或 !=,不能使用>或<的,但是在开发环境中,我们需要对多个对象进行排序,也就需要比较对象的大小,针对此类问题,可以使用以下两个接口实现:Comparable、Comparator
    • 自然排序:java.lang.Comparable
    • 定制排序:java.util.Comparator
    • Comparable接口的使用举例:
      • 像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了两个对象大小的方式
      • 像String、包装类重写 compareTo()方法以后,进行了从小到大的排列
      • 重写compareTo(obj)的规则:
        • 如果当前对象this大于形参对象obj,则返回正整数
        • 如果当前对象this小于形参对象obj,则返回负整数
        • 如果当前对象this等于形参对象obj,则返回0
package www.bh.c.datanewtest;
import java.util.Arrays;

public class Test07 {
    public static void main(String[] args) {
        String[] arr=new String[]{"AA","DD","HH","BB","MM","TT"};
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));//[AA, BB, DD, HH, MM, TT]
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值