Java中的日期时间API汇总

1.System类

System类提供的public static long currentTimeMillis()用来返回当前时间与1970年1月1日0时0分0秒以毫秒为单位的时间差。

  • 此方法适用于计算时间差
@Test
public void test(){
    long time = System.currentTimeMillis();
    //称为时间戳
    System.out.println(time);
}

2.Date

Date有两个位置,一个是java.util.Date类,还有一个是他的子类java.sql.Date类。

关注以下三点:

  1. 👇两个构造器的使用(见代码)
  • 创建一个对应当前时间的Date对象
  • 创建指定毫秒数的对象
  • 可以创建指定年月日的对象,但已经不建议使用
  1. 👇两个方法的使用
  • toString():显示当前的年月日时分秒
  • getTime():返回当前时间与1970年1月1日0时0分0秒以毫秒为单位的时间差
  1. java.sql.Date对应这数据库中的日期类型的变量(和数据库交互时用)

如何将util.Date对象转换为sql.Date对象

    @Test
    public void test1(){
        //构造器一:new Date():创建一个对应当前时间的Date对象
        Date date1 = new Date();
        System.out.println(date1.toString()); //Fri Dec 23 13:34:11 CST 2022
        System.out.println(date1.getTime());

        //构造器二:创建指定毫秒数的对象
        //可以创建指定年月日的对象,但已经不建议使用
        Date date2 = new Date(1671773707455L);
//      Date date = new Date(2010, 1, 1);
        System.out.println(date2.toString());

        //创建java.sql.Date对象
        java.sql.Date date3 = new java.sql.Date(35431895632L);
        System.out.println(date3.toString());
        
        //将util.Date对象转换为sql.Date对象
        //情况一:
        Date date4 = new java.sql.Date(35431895632L);
        java.sql.Date date5 = (java.sql.Date)date4;
        //情况二:
        Date date6 = new Date();
        java.sql.Date date7 = new java.sql.Date(date6.getTime());
    }

3.SimpleDateFormat

使用:对日期Date类的格式化和解析

🎈关注两个操作:

  1. 格式化:日期 —> 字符串(format方法)
  2. 解析:格式化的逆过程,字符串 —> 日期(parse方法)

🎈实例化:通过无参或有参的构造器

@Test
public void test() throws ParseException {
    //实例化SimpleDateFormat
    SimpleDateFormat sdf = new SimpleDateFormat();

    //格式化:日期 ---> 字符串
    Date date = new Date();
    System.out.println(date);
    String format = sdf.format(date); //格式化
    System.out.println(format);

    //解析:格式化的逆过程,字符串 ---> 日期
    String s = "22-01-01 上午08:00";
    Date date1 = sdf.parse(s);
    System.out.println(date1);
}

注意:开发中常用的SimpleDateFormat构造器

  • yyyy-MM-dd hh:mm:ss 年月日时分秒
//指定方式格式化:调用带参的构造器
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format1 = sdf1.format(date);
System.out.println(format1);
//指定方式解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),否则抛异常
Date date2 = sdf1.parse("2022-01-01 00:00:00");
System.out.println(date2);

3.1练习

  1. 字符串“2020-09-08”转换为java.sql.Date
@Test
public void test() throws ParseException {
    String s = "2020-09-08";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdf.parse(s);
    java.sql.Date date1 = new java.sql.Date(date.getTime());
    System.out.println(date1);
}
  1. 经典:三天打鱼两天晒网,从1990-01-01开始,到2020-01-01这一天,是打渔还是晒网?
@Test
public void test(){
    Date d1 = new Date(1990 - 01 - 01);
    long i = d1.getTime();
    Date d2 = new Date(2020 - 01 - 01);
    long j = d2.getTime();
    long x = ((j-i)/(1000*60*60*24)+1) % 5;
    if (x<=3 && x != 0){
        System.out.println("打渔");
    } else {
        System.out.println("晒网");
    }
}

另外一种方法:可以先计算1990-01-01到2019-12-31的天数,直接365 * 年份,然后看这些年有多少是闰年就加多少个1。


4.Calendar日历

Calendar类是一个抽象类,用于完成日期字段之间相互操作的功能。

4.1 获取Calendar实例的方法

  • 使用Calendar.getInstance()方法
  • 调用它的子类GregorianCalendar构造器
@Test
public void test(){
    //实例化
    //方式一:创建其子类(GregorianCalendar)的对象
    //方式二:调用其静态方法getInstance()
    Calendar calendar = Calendar.getInstance();
}

4.2 Calendard的常用方法

  • get()
  • set()
  • add()
  • getTime()
  • setTime()
@Test
public void test(){
    //1.实例化
    //方式一:创建其子类(GregorianCalendar)的对象
    //方式二:调用其静态方法getInstance()
    Calendar calendar = Calendar.getInstance();

    //2.常用方法
    //get()
    int days = calendar.get(Calendar.DAY_OF_MONTH);//求这个月的第几天
    System.out.println(days);
    System.out.println(calendar.get(Calendar.DAY_OF_YEAR));//求这一年的第几天

    //set()
    //calendar可变性
    calendar.set(Calendar.DAY_OF_MONTH,22); //将这个月的第几天设置成指定的第几天,已经修改了而不是创建新的
    days = calendar.get(Calendar.DAY_OF_MONTH);
    System.out.println(days);

    //add()
    calendar.add(Calendar.DAY_OF_MONTH,-3);//将这个月的第几天减了3天
    days = calendar.get(Calendar.DAY_OF_MONTH);
    System.out.println(days);

    //getTime():日历类---> Date
    Date date = calendar.getTime();
    System.out.println(date);

    //setTime():Date ---> 日历类
    Date date1 = new Date();
    calendar.setTime(date1);
    days = calendar.get(Calendar.DAY_OF_MONTH);
    System.out.println(days);
}

注意:

  • 获取月份时:一月是0,二月是1,以此类推,12月是11
  • 获取星期时:周日是1,周一是2,…,周六是7

5.几个Local时间类

这些是JDK8之后新增的API

LocalDate、LocalTime、LocalDateTime;其中LocalDateTime使用频率更高

5.1 实例化方式

  1. now():获取当前的日期、时间、日期和时间
  2. of():获取指定的日期年月日时分秒。没有偏移量
@Test
public void test(){
    //实例化方式1: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);

    //实例化方式2:of():设置指定的年月日时分秒,没有偏移量
    LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 1, 00, 00, 10);
    System.out.println(localDateTime1);
}

5.2常用方法

  1. getXxx():获取
LocalDateTime localDateTime = LocalDateTime.now(); //获取当前年月日时分秒毫秒
//getXxx()
System.out.println(localDateTime.getDayOfMonth()); //获取当月第几天
System.out.println(localDateTime.getMonth()); //获取第几个月(英文)
System.out.println(localDateTime.getMonthValue()); //获取当前月的数值
System.out.println(localDateTime.getDayOfWeek()); //获取当前是星期几
System.out.println(localDateTime.getDayOfYear()); //获取今天是这一年的第几天
System.out.println(localDateTime.getMinute()); //获取现在是这一小时的第几分钟
  1. withXxx():设置(但不可变)
//withXxx
LocalDate localDate1 = localDate.withDayOfMonth(20); //把当前这个月的第几天设置成第20天
System.out.println(localDate1);
LocalDateTime localDateTime2 = localDateTime.withHour(5); //把现在是今天的第几个小时设置成第五个小时
System.out.println(localDateTime2);
  1. plusXxx():在时间日期上做加法(不可变)
  2. minusXxx():在时间日期上做减法(不可变)
LocalDateTime localDateTime3 = localDateTime.plusMonths(2);
System.out.println(localDateTime);
System.out.println(localDateTime3);

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

6.Instant

Instant:时间线上的一个瞬时点。这可能被用来记录应用程序中的事件时间戳

6.1实例化

now():获取的是中时区(本初子午线)的时间,比北京时间早了8小时

如果想用东八区的时间,就用实例化的对象调用atOffset(ZoneOffset.ofHours(8))

//实例化:获取本初子午线的时间
Instant instant = Instant.now(); //获取的是中时区(本初子午线)的时间,比北京时间早了8小时
System.out.println(instant);
//添加偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);

6.2常用方法

  1. toEpochMilli():获取对应的毫秒数,对应1970-1-1 00:00:00
long milli = instant.toEpochMilli();
System.out.println(milli);
  1. 类.ofEpochMilli(毫秒数):获取毫秒数对应的时间

7.DateTimeFormatter

用来格式化或解析日期、时间

类似于SimpleDataFormat

7.1实例化与格式化、解析

  1. 预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
  2. 本地化相关的格式。如:ofLocalizedDateTime()是日期时间、ofLocalizedDate()只是日期
  3. 自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
@Test
public void test2(){
    //方式一:预定义的标准格式
    DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
    //格式化:日期--->字符串
    LocalDateTime localDateTime = LocalDateTime.now();
    String s = formatter.format(localDateTime);
    System.out.println(localDateTime);
    System.out.println(s);
    //解析:字符串--->日期
    TemporalAccessor parse = formatter.parse("2022-01-01T00:00:16.535");
    System.out.println(parse);


    //方式二:本地化相关的格式
    //   FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
    DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
    //格式化
    String s1 = formatter1.format(localDateTime);
    System.out.println(s1);
    //   FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
    DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
    //格式化
    String s2 = formatter2.format(LocalDate.now());
    System.out.println(s2);


    //方式三:自定义的格式
    DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    //格式化
    String s3 = formatter3.format(LocalDateTime.now());
    System.out.println(s3);
    //解析
    TemporalAccessor parse1 = formatter3.parse("2022-01-01");
    System.out.println(parse1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Perfectkn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值