当前位置: 首页 > news >正文

java获取当前时间的方法:LocalDateTime、Date、Calendar,以及三者的比较

文章目录

  • 前言
  • 一、LocalDateTime
    • 1.1 获取当前时间LocalDate.now()
    • 1.2 获取当前时间的年、月、日、时分秒localDateTime.getYear()……
    • 1.3 给LocalDateTime赋值LocalDateTime.of()
    • 1.4 时间与字符串相互转换LocalDateTime.parse()
    • 1.5 时间运算——加上对应时间LocalDateTime.now().plusYears(2)
    • 1.6 时间运算——减去对应时间LocalDateTime.now().minusYears(2)
    • 1.7 两个时间比较LocalDateTime.now().compareTo()
    • 1.8 利用Duration计算时间差Duration.between(of,now).toMillis()
    • 1.9 改变当前时间的年、月、日、时、分、秒LocalDateTime.now().withYear(2060)
    • 1.10 自定义输出的格式DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    • 1.11 LocalDateTime的with()方法
    • 1.12 两个日期前后的比较与判断LocalDateTime.now().isBefore()
  • 二、Util获取当前时间
    • 2.1 Date
    • 2.1.1 Date获取当前时间
    • 2.1.1 Date存在的缺陷
    • 2.2 Calendar
  • 三、System.currentTimeMillis()
  • 总结


前言


在开发时我们经常需要获取当前时间或者对时间进项处理(在某个时间的基础上增加或者减少),java获取时间的方法比较多,有LocalDateTime、Date、Calendar等,其中LocalDateTime是java8的新特性,相比较其它两个而言,LocalDateTime有很多优势,这也是最推荐使用的方法。
下面我们先来介绍一个LocalDateTime的用法,然后介绍Date、Calendar的用法,最后比较它们的区别。

一、LocalDateTime

JDK1.8版本中新引入的API,加强了对时间的管理,有很多特别好用的时间运算方法,而且是线程安全的。

1.1 获取当前时间LocalDate.now()

    @Testvoid test() {LocalDate localDate = LocalDate.now();LocalTime localTime = LocalTime.now();LocalDateTime localDateTime = LocalDateTime.now();System.out.println("localDate:"+localDate);//2023-02-22System.out.println("localTime:"+localTime);//17:25:36.590System.out.println("localDateTime:"+localDateTime);//2023-02-22T17:25:36.590}

输出结果:
在这里插入图片描述
可以看到不用做格式转换就可以得到可读性很高的日期格式。
注意:ISO 8601规定的日期和时间分隔符是T。标准格式如下:

日期:yyyy-MM-dd
时间:HH:mm:ss
带毫秒的时间:HH:mm:ss.SSS
日期和时间:yyyy-MM-dd'T'HH:mm:ss
带毫秒的日期和时间:yyyy-MM-dd'T'HH:mm:ss.SSS

1.2 获取当前时间的年、月、日、时分秒localDateTime.getYear()……

    @Testvoid test() {LocalDateTime localDateTime = LocalDateTime.now(); // 获取当前时间int year = localDateTime.getYear(); // 获取年份 2023int month = localDateTime.getMonthValue(); // 获取月份 2int day = localDateTime.getDayOfMonth(); // 获取月中的天数 22int hour = localDateTime.getHour(); // 获取当前的小时 17int minute = localDateTime.getMinute(); // 获取当前分钟 33int second = localDateTime.getSecond(); // 获取当前秒数 22System.out.println(year);System.out.println(month);System.out.println(day);System.out.println(hour);System.out.println(minute);System.out.println(second);}

输出结果:
在这里插入图片描述

1.3 给LocalDateTime赋值LocalDateTime.of()

    void test() {LocalDateTime of = LocalDateTime.of(2023,2,22,22,22,22);System.out.println(of); // 输出2023-02-22T22:22:22}

输出结果:
在这里插入图片描述

1.4 时间与字符串相互转换LocalDateTime.parse()

    @Testvoid test() {// 将字符串转换为指定格式的时间(格式要和给定的格式一致,不然会报错)LocalDateTime parse = LocalDateTime.parse("2023-02-22 22:22:22", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));LocalDateTime parse1 = LocalDateTime.parse("2023 02 22 22:22:22", DateTimeFormatter.ofPattern("yyyy MM dd HH:mm:ss"));LocalDateTime parse2 = LocalDateTime.parse("2023.02.22 22:22:22", DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"));System.out.println(parse); // 输出2023-02-22T22:22:22System.out.println(parse1); // 输出2023-02-22T22:22:22System.out.println(parse2); // 输出2023-02-22T22:22:22// 时间转字符串LocalDateTime now = LocalDateTime.now();DateTimeFormatter of = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String dateTime = now.format(of);System.out.println(dateTime); // 输出 2023-02-22 17:56:18}

输出结果:
在这里插入图片描述

1.5 时间运算——加上对应时间LocalDateTime.now().plusYears(2)

LocalDateTime提供了对日期和时间进行加减的非常简单的链式调用,让时间运算变得非常简单:

    @Testvoid test() {LocalDateTime now = LocalDateTime.now(); // 当前时间2023-02-22T18:00:19.352LocalDateTime plusYears= now.plusYears(2); // 在当前时间加上2年2025-02-22T18:00:19.352LocalDateTime plusMonths= now.plusMonths(2);// 在当前时间商加上2月2023-04-22T18:00:19.352LocalDateTime plusDays= now.plusDays(2); // 在当前时间加上2天2023-02-24T18:00:19.352LocalDateTime plusHours= now.plusHours(2); // 在当前时间加上2个小时2023-02-22T20:00:19.352LocalDateTime plusMinutes= now.plusMinutes(30); // 在当前时间加上30分钟2023-02-22T18:30:19.352LocalDateTime plusSeconds = now.plusSeconds(30); // 在当前时间加上30秒2023-02-22T18:00:49.352System.out.println(now);System.out.println(plusYears);System.out.println(plusMonths);System.out.println(plusDays);System.out.println(plusHours);System.out.println(plusMinutes);System.out.println(plusSeconds);}

输出结果:
在这里插入图片描述

1.6 时间运算——减去对应时间LocalDateTime.now().minusYears(2)

    @Testvoid test() {LocalDateTime now = LocalDateTime.now(); // 当前时间LocalDateTime minusYears = now.minusYears(2); // 在当前时间减上2年LocalDateTime minusMonths = now.minusMonths(2);// 在当前时间商减上2月LocalDateTime minusDays = now.minusDays(2); // 在当前时间减上2天LocalDateTime minusHours = now.minusHours(2); // 在当前时间减上2个小时LocalDateTime minusMinutes = now.minusMinutes(30); // 在当前时间减上30分钟LocalDateTime minusSeconds = now.minusSeconds(30); // 在当前时间减上30秒System.out.println("now:" + now);System.out.println("minusYears:" + minusYears);System.out.println("minusMonths:" + minusMonths);System.out.println("minusDays:" + minusDays);System.out.println("minusHours:" + minusHours);System.out.println("minusMinutes:" + minusMinutes);System.out.println("minusSeconds:" + minusSeconds);}

输出结果:
在这里插入图片描述

1.7 两个时间比较LocalDateTime.now().compareTo()

    @Testvoid test() {LocalDateTime now = LocalDateTime.now(); // 当前时间LocalDateTime now1 = now.plusYears(5); // 在当前时间加上5年//  给LocalDateTime 赋值LocalDateTime of = LocalDateTime.of(2023,2,2,22,22,22);LocalDateTime of1 = LocalDateTime.of(2023,8,5,1,1,1);//两个时间作比较,第一个时间减去第二个时间(如果年份相同,比较月份,月份相同比较天数,以此类推)int compareTo = now1.compareTo(now);int compareTo1 = now.compareTo(now1);int compareTo2 = now.compareTo(of);int compareTo3 = now.compareTo(of1);System.out.println(now);   // 输出 2023-02-22T20:19:44.112vSystem.out.println(now1); // 输出 2028-02-22T20:19:44.112System.out.println(of); // 输出 2023-02-02T22:22:22System.out.println(of1); // 输出 2023-08-05T01:01:01System.out.println(compareTo); // 输出 5System.out.println(compareTo1); // 输出 -5System.out.println(compareTo2); // 输出 20System.out.println(compareTo3); // 输出 -6}

输出结果:

1.8 利用Duration计算时间差Duration.between(of,now).toMillis()

注意没有计算相差的年和秒值,对于要计算相差的秒数,可以利用计算毫秒来进行转换。

    @Testvoid test() {LocalDateTime now = LocalDateTime.now(); // 当前时间//  给LocalDateTime 赋值LocalDateTime of = LocalDateTime.of(2022,2,22,2,2,2);Duration duration = Duration.between(of,now); // 后面减去前面long toDays = Duration.between(of,now).toDays(); //相差的天数long toHours = Duration.between(of,now).toHours();//相差的小时数long toMinutes = Duration.between(of,now).toMinutes();//相差的分钟数long toMillis = Duration.between(of,now).toMillis();//相差毫秒数long toNanos = Duration.between(of,now).toNanos();//相差的纳秒数System.out.println("toDays:"+ toDays); // 输出 toDays:365System.out.println("toHours:"+ toHours); // 输出 toHours:8778System.out.println("toMinutes:"+ toMinutes); // 输出 toMinutes:526732System.out.println("toMillis:"+ toMillis); // 输出 toMillis:31603973840System.out.println("toNanos:"+ toNanos); // 输出 toNanos:31603973840000000}

输出结果:
在这里插入图片描述

1.9 改变当前时间的年、月、日、时、分、秒LocalDateTime.now().withYear(2060)

    @Testvoid test() {LocalDateTime now = LocalDateTime.now(); // 当前时间LocalDateTime withYear = now.withYear(2060); // 改变当前年份(变成2060年)LocalDateTime withMonth = now.withMonth(12); // 改变当前月份(变成12月份)LocalDateTime withDayOfMonth = now.withDayOfMonth(28); //改变当前天数(变成28日)LocalDateTime withHour = now.withHour(23); // 改变当前小时数(变成23时)LocalDateTime withMinute = now.withMinute(30); // 改变当前分钟(变成30分钟)LocalDateTime withSecond = now.withSecond(23); // 改变当前小时数(变成23时)LocalDateTime withDayOfYear = now.withDayOfYear(60); // 从一月一号开始加上60天System.out.println(now);System.out.println("withYear:"+ withYear);System.out.println("withMonth:"+ withMonth);System.out.println("withDayOfMonth:"+ withDayOfMonth);System.out.println("withHour:"+ withHour);System.out.println("withMinute:"+ withMinute);System.out.println("withSecond:"+ withSecond);System.out.println("withDayOfYear:"+ withDayOfYear);}

输出结果:
在这里插入图片描述

1.10 自定义输出的格式DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”);

    @Testvoid test() {// 自定义格式化:DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss");System.out.println("自定义格式yyyy/MM/dd HH:mm:ss :"+dtf.format(LocalDateTime.now()));System.out.println("自定义格式yyyy.MM.dd HH:mm:ss :"+dtf1.format(LocalDateTime.now()));// 用自定义格式解析:LocalDateTime dt2 = LocalDateTime.parse("2020/10/20 15:16:17", dtf);System.out.println("格式解析:"+dt2);}

输出结果:
在这里插入图片描述

1.11 LocalDateTime的with()方法

// 本月第一天0:00时刻:
LocalDateTime firstDay = LocalDate.now().withDayOfMonth(1).atStartOfDay();
// 本月最后1天:
LocalDate lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
// 下月第1天:
LocalDate nextMonthFirstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth());
// 本月第1个周一:
LocalDate firstWeekday = LocalDate.now().with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));

输出结果:

1.12 两个日期前后的比较与判断LocalDateTime.now().isBefore()

    @Testvoid test() {//判断两个时间点的前后LocalDateTime now = LocalDateTime.now();LocalDateTime target = LocalDateTime.of(2022, 2, 22, 22, 22, 22);boolean isBefore = now.isBefore(target);System.out.println("now:"+now);System.out.println("target:"+target);System.out.println("isBefore:"+isBefore);System.out.println(LocalDate.now().isBefore(LocalDate.of(2022, 2, 22)));System.out.println(LocalTime.now().isAfter(LocalTime.parse("08:15:00")));}}

输出结果:
在这里插入图片描述

二、Util获取当前时间

2.1 Date

2.1.1 Date获取当前时间

    @Testvoid test() {Date date = new Date(); // 返回当前时间戳格式SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 改变格式System.out.println(dateFormat.format(date)); // 获取当前时间  2023-02-22 21:24:53}

2.1.1 Date存在的缺陷

如果不格式化,打印出的日期可读性差:

    @Testvoid test() {Date date = new Date(); // 返回当前时间戳格式System.out.println(date); // 获取当前时间  Wed Feb 22 21:34:18 CST 2023}

通常会使用SimpleDateFormate来实现格式化,但是sdf最大的问题是线程不安全的。

2.2 Calendar

    @Testvoid test() {Calendar cal= Calendar.getInstance(); // 返回当前时间戳格式SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 改变格式System.out.println(dateFormat.format(cal.getTime())); // 获取当前时间int y=cal.get(Calendar.YEAR); // 获取当前年份int m=cal.get(Calendar.MONTH); // 获取当前月份int d=cal.get(Calendar.DATE); // 获取当前日期int h=cal.get(Calendar.HOUR_OF_DAY); // 获取当前小时int mi=cal.get(Calendar.MINUTE); // 获取当前分钟int s=cal.get(Calendar.SECOND); // 获取当前秒数System.out.println("现在时刻是"+y+"年"+m+"月"+d+"日"+h+"时"+mi+"分"+s+"秒");}

三、System.currentTimeMillis()

SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z"); // 改变格式
Date date = new Date(System.currentTimeMillis()); // 返回当前时间戳格式
System.out.println(formatter.format(date)); // 获取当前时间

总结

LocalDateTime获取时间以及计算都非常方便,而且是线程安全的,简易使用LocalDateTime。

http://www.lryc.cn/news/16828.html

相关文章:

  • npm link
  • Docker 如何配置镜像加速
  • 阅读笔记7——Focal Loss
  • ZCMU--5009: 龙虎斗
  • 创建项目(React+umi+typeScript)
  • FISCO BCOS(二十七)———java操作WeBase
  • 失眠时还在吃它?有风险,你了解过吗
  • 星戈瑞收藏Sulfo-CY7 amine/NHS ester/maleimide小鼠活体成像染料标记反应
  • 守护最后一道防线:Coremail邮件安全网关推出邮件召回功能
  • Python实战之小说下载神器(二)整本小说下载:看小说不用这个程序,我实在替你感到可惜*(小说爱好者必备)
  • ChatGPT三个关键技术
  • 考试系统 (springboot+vue前后端分离)
  • ChatGPT告诉你:项目管理能干到60岁吗?
  • Python自动化测试框架【Allure-pytest功能特性介绍】
  • ToB 产品拆解—Temu 商家管理后台
  • Android Studio的笔记--socket通信
  • @Async 注解
  • Redis:缓存穿透、缓存雪崩和缓存击穿(未完待续)
  • HIVE 基础(四)
  • 整型在内存中的存储(详细剖析大小端)——“C”
  • PS_高低频和中性灰——双曲线
  • Vim 命令速查表
  • Java重要基本概念理解
  • 逆向工具之 unidbg 执行 so
  • zk-STARK/zk-SNARK中IP,PCP,IPCP,IOP,PIOP,LIP,LPCP模型介绍
  • StreamAPI
  • MySQl高可用集群搭建(MGR + ProxySQL + Keepalived)
  • java+Selenium+TestNg搭建自动化测试架构(3)实现POM(page+Object+modal)
  • oracle11g忘记system密码,重置密码
  • 黑马 Vue 快速入门 笔记