JDK8的时间日期处理类

包所在位置 java.time

LocalDate:不包含具体时间的日期。
LocalTime:不含日期的时间。
LocalDateTime:包含了日期及时间。

创建时间对象(因为是静态方法不能创建对象)
LocalDateTime localDateTime=LocalDateTime.now();
在这里插入图片描述

线程安全的时间日期:
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern(“yyyy-MM-dd HH-mm-ss”);

创建时间线程安全的时间日期对象:
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern(“yyyy-MM-dd HH-mm-ss”);
String times=dateTimeFormatter.format(localDateTime);

 public static void main(String[] args){

        //jdk8版本的时间
        LocalDateTime localDateTime=LocalDateTime.now();
        System.out.println(localDateTime);
        System.out.println("现在年份"+localDateTime.getYear());
        System.out.println("现在月份"+localDateTime.getMonth());
        System.out.println("现在月份(数字)"+localDateTime.getMonthValue());
        System.out.println("现在小时"+localDateTime.getHour());
        System.out.println("现在是当年的第几天"+localDateTime.getDayOfYear());
        System.out.println("现在是当月的几号"+localDateTime.getDayOfMonth());
        System.out.println("现在是星期几"+localDateTime.getDayOfWeek());
        System.out.println("===========================================================");

        //加减年份,月份 比较日期前后
        LocalDateTime changedate=localDateTime.plusYears(1);
        System.out.println("加后的年份"+changedate.getYear());
        LocalDateTime changemonth=changedate.withMonth(5);
        System.out.println("修改后的月份"+changemonth.getMonthValue());
        System.out.println("添加后的日期是否在之前日期之后"+changedate.isAfter(localDateTime));
        System.out.println("===========================================================");

        //时间格式设置
        DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
        String times=dateTimeFormatter.format(localDateTime);
        System.out.println("线程安全的日期与时间"+times);
        //自定义时间
        LocalDateTime changeday=LocalDateTime.of(2023,10,1,5,15,30);
        System.out.println("自定义时间"+changeday);
        System.out.println("===========================================================");

        //两时间比较
        Duration duration=Duration.between(localDateTime,changeday);
        System.out.println("相差的天数"+duration.toDays());
        System.out.println("相差的小时"+duration.toHours());
        System.out.println("相差的分钟"+duration.toMinutes());
        System.out.println("相差的毫秒"+duration.toMillis());
        System.out.println("相差的纳秒"+duration.toNanos());

    }

效果截图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值