Java中第三代日期类LocalDateTime的详细使用

第三代日期类的概述:
在这里插入图片描述

下面通过代码进行演示使用:

public class LocalDate_ {
    
    
    public static void main(String[] args) {
    
    
        //第三日期
        //1.使用now() 返回表示当前日期时间的对象
        LocalDateTime localDateTime = LocalDateTime.now();//LocalDate.now();//LocalTime.now();
        System.out.println(localDateTime);

        //2.使用DateTimeFormatter对象来进行格式化
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dtf.format(localDateTime);
        System.out.println("格式化的日期:" + format);

        System.out.println("年=" + localDateTime.getYear());
        System.out.println("月=" + localDateTime.getMonth());
        System.out.println("月=" + localDateTime.getMonthValue());
        System.out.println("日=" + localDateTime.getDayOfMonth());
        System.out.println("时=" + localDateTime.getHour());
        System.out.println("分=" + localDateTime.getMinute());
        System.out.println("秒=" + localDateTime.getSecond());


        LocalDate localDate = LocalDate.now(); //获取年月日

        //提供了plus和minus方法可以对当前时间进行加或减
        //看看890天后,是什么时候
        LocalDateTime localDateTime1 = localDateTime.plusDays(890);
        System.out.println("890天后:" + dtf.format(localDateTime1));

        LocalDateTime localDateTime2 = localDateTime.minusMinutes(3465);
        System.out.println("3465分钟前 日期为:" + dtf.format(localDateTime2));
    }
}

输出结果:

2022-03-19T12:10:51.333
格式化的日期:2022-03-19 12:10:51
年=2022
月=MARCH
月=3
日=19
时=12
分=10
秒=51
890天后:2024-08-25 12:10:51
3465分钟前 日期为:2022-03-17 02:25:51

第三代日期类的时间戳:Instant

在这里插入图片描述
演示代码如下:

public class Instant_ {
    
    
    public static void main(String[] args) {
    
    
        //Instant时间戳
        Instant instant = Instant.now();
        System.out.println(instant);

        //通过Date.from()方法 可以把Instant转成Date
        Date date = Date.from(instant);
        System.out.println(date);

        //通过date的toInstant()可以把date转换成Instant对象
        Instant instant1 = date.toInstant();
        System.out.println(instant1);
    }
}

输出结果如下:

2022-03-19T04:13:46.033Z
Sat Mar 19 12:13:46 CST 2022
2022-03-19T04:13:46.033Z

猜你喜欢

转载自blog.csdn.net/lu202032/article/details/123592174