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

【高级编程】实用类详解(下)万字整理Java时间日期类 JDK8新日期

文章目录

    • 日期时间
      • Date
      • SimpleDateFormat
      • Calendar
    • JDK8 新日期
      • LocalDateTime&LocalDate&LocalTime
      • DateTimeFormater
      • 计算
      • Period&Duration
      • zonedDateTime
      • Instant
      • 类型转换
    • 注意事项


日期时间

Date

java.util.Date 类:表示日期和时间。提供操作日期和时间各组成部分的方法。

Date 对象记录的时间是用毫秒值来表示的。Java 语言规定,1970年1月1日0时0分0秒认为是时间的起点,此时记作0,1 秒 =1000 毫秒,1000就表示1970年1月1日0时0分1秒。

// 创建日期对象
Date date = new Date(); 
常见方法说明
public long getTime()返回从1970年1月1日00:00:00走到此刻的总的毫秒数
public void setTime(long time)设置日期对象的时间为当前时间毫秒值对应的时间

SimpleDateFormat

java.text.SimpleDateFormat 类:转换 Date 对象表示日期时间的显示格式。用于定制日期时间的格式。

  • Date 对象转换为指定格式的日期字符串:日期格式化
  • 指定格式的日期符串转换为 Date 对象:日期解析
格式化时间的方法说明
public final string format(Date date)将日期格式化成日期/时间字符串
public final string format(0bject time)将时间毫秒值式化成日期/时间字符串
解析方法说明
public Date parse(String source)把字符串时间解析成日期对象
字母	  表示含义
yyyy	年
MM		月
dd		日
HH		时
mm		分
ss		秒
SSS		毫秒
"2022年12月12日" 的格式是 "yyyy年MM月dd日"
"2022-12-12 12:12:12" 的格式是 "yyyy-MM-dd HH:mm:ss"
// 按照上面的格式可以任意拼接,但是字母不能写错
// 获得当前时间
Date date = new Date();
System.out.println(date);// 创建格式化日期工具 并指定格式 yyyy-MM-dd HH:mm:ss.SSS
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 调用format方法,格式化日期,并返回字符串
String strdate = sdf.format(date);
System.out.println("格式化后:" + strdate);// 将字符串转换为日期类型
try {Date br = sdf.parse("1991-12-31 01:01:01");System.out.println(br);
} catch (ParseException e) {throw new RuntimeException(e);
}
Thu Sep 05 10:45:09 CST 2024
格式化后:2024-09-05 10:45:09
Tue Dec 31 01:01:01 CST 1991

Calendar

java.util.Calendar 抽象类,用于设置和获取日期/时间数据的特定部分。可以直接对日历中的年、月、日、时、分、秒等进行运算。

方法或属性说明
public static Calendar getInstance()获取当前日历对象
public int get(int field)获取日历中的某个信息。
public final Date getTime()获取日期对象。
public long getTimeInMillis()获取时间毫秒值
public void set(int field,int value)修改日历的某个信息。
public void add(int field,int amount)为某个信息增加/减少指定的值
MONTH指示月
DAY_OF_MONTH指示一个月中的某天
DAY_OF_WEEK指示一个星期中的某天

calendar是可变对象,一旦修改后其对象本身表示的时间将产生变化。

// 在Calendar类中,月份是从 0 开始计数的。以下是每个月份对应的常量及其对应的数字:
Calendar.JANUARY: 0
Calendar.FEBRUARY: 1
Calendar.MARCH: 2
Calendar.APRIL: 3
Calendar.MAY: 4
Calendar.JUNE: 5
Calendar.JULY: 6
Calendar.AUGUST: 7
Calendar.SEPTEMBER: 8
Calendar.OCTOBER: 9
Calendar.NOVEMBER: 10
Calendar.DECEMBER: 11
Calendar cal = Calendar.getInstance();System.out.println(cal.get(Calendar.YEAR)); // 年
System.out.println(cal.get(Calendar.MONTH) + 1); // 月 (0-11, 所以加1)
System.out.println(cal.get(Calendar.DATE)); // 日
System.out.println(cal.get(Calendar.HOUR_OF_DAY)); // 时 (24小时制)
System.out.println(cal.get(Calendar.MINUTE)); // 分
System.out.println(cal.get(Calendar.SECOND)); // 秒
System.out.println(cal.get(Calendar.MILLISECOND)); // 毫秒

JDK8 新日期

JDK 8 引入了全新的日期和时间 API,主要集中在 java.time 包中。它解决了旧版 java.util.Datejava.util.Calendar 的一些问题,并提供了更强大和易用的功能。主要类包括:

  • LocalDateTime:表示日期和时间,但不包含时区信息。
  • LocalDate:仅表示日期,不包含时间和时区信息。
  • LocalTime:仅表示时间,不包含日期和时区信息。
  • ZonedDateTime:表示日期、时间和时区,适用于跨时区操作。
  • Period:表示日期间隔,通常用于计算两个日期之间的差异。
  • Duration:表示时间间隔,用于计算两个时间点之间的时长。
  • Instant:表示时间戳,基于 UTC 时间。适用于需要精确的时间点。

LocalDateTime&LocalDate&LocalTime

当前日期时间

// 获取当前日期
LocalDate currentDate = LocalDate.now();
System.out.println("当前日期: " + currentDate);// 获取当前时间
LocalTime currentTime = LocalTime.now();
System.out.println("当前时间: " + currentTime);// 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("当前日期和时间: " + currentDateTime);
当前日期: 2024-09-05
当前时间: 11:54:48.556
当前日期和时间: 2024-09-05T11:54:48.556
  • LocalDate类的基本使用
方法名说明
public int getYear()获取年
public int getMonthValue()获取月份(1-12)
public int getDayOfMonth()获取日
public int getDayOfYear()获取当前是一年中的第几天
public DayOfWeek getDayOfWeek()获取星期几: ld.getDayOfWeek().getValue()
方法名说明
withYear、withMonth、withDayOfMonth、withDayOfYear直接修改某个信息,返回新日期对象
plusYears、plusMonths、plusDays、plusWeeks把某个信息加多少,返回新日期对象
minusMonths、minusDays、minusWeeks把某个信息减多少,返回新日期对象
equals isBefore isAfter判断两个日期对象,是否相等,在前还是在后
  • LocalTime类的基本使用
方法名说明
public int getHour()获取小时
public int getMinute()获取分
public int getSecond()获取秒
public int getNano()获取纳秒
方法名说明
withHour、withMinute、withSecond、withNano时间,返回新时间对象
plusHours、plusMinutes、plusSeconds、plusNanos把某个信息加多少,返回新时间对象
minusHours、minusMinutes、minusSeconds、minusNanos把某个信息减多少,返回新时间对象
equals isBefore isAfter判断两个日期对象,是否相等,在前还是在后
  • LocalDateTime类的基本使用

LocalDateTime的转换成LocalDate、LocalTime

方法名说明
public LocalDate toLocalDate()转换成一个LocalDate 对象
public LocalTime toLocalTime()转换成一个LocalTime 对象

DateTimeFormater

格式化

DateTimeFormater 格式化器。新增的日期格式化类,可以从来对日期进行格式化和解析。代替了原来的 SimpleDateFormat 类。

方法名说明
public static DateTimeFormater ofPattern(时间格式)获取格式化器对象
public String format(时间对象)格式化时间

LocalDateTime 提供的格式化、解析时间的方法

方法名说明
public String format(DateTimeFormatter formatter)格式化时间
public static LocalDateTime parse(CharSequence. text,DateTimeFormatter formatter)解析时间
// 创建一个DateTimeFormatter对象,指定日期时间的格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");// 格式化当前日期时间
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("格式化后的日期和时间: " + formattedDateTime);// 使用预定义的格式
String isoDateTime = currentDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("ISO格式的日期和时间: " + isoDateTime);
格式化后的日期和时间: 2024-09-05 11:54:48
ISO格式的日期和时间: 2024-09-05T11:54:48.556

计算

// 日期加减
LocalDate futureDate = currentDate.plusDays(5);
LocalDate pastDate = currentDate.minusMonths(1);
System.out.println("未来5天后的日期: " + futureDate);
System.out.println("1个月前的日期: " + pastDate);// 时间加减
LocalTime timePlusHours = currentTime.plusHours(2);
LocalTime timeMinusMinutes = currentTime.minusMinutes(30);
System.out.println("2小时后的时间: " + timePlusHours);
System.out.println("30分钟前的时间: " + timeMinusMinutes);
未来5天后的日期: 2024-09-10
1个月前的日期: 2024-08-05
2小时后的时间: 13:54:48.556
30分钟前的时间: 11:24:48.556

Period&Duration

计算时间间隔

Period 类和 Duration 类都可以用来对计算两个时间点的时间间隔。

  • Period:计算日期间隔(年、月、日)
  • Duration:计算时间间隔(时、分、秒、纳秒)

Period 可以用来计算两个日期之间相隔的年、相隔的月、相隔的日。

只能两个计算 LocalDate 对象之间的间隔

Period period = Period.between(LocalDate.of(2023, 1, 1), LocalDate.of(2023, 12, 31));
System.out.println("年份差异: " + period.getYears());
System.out.println("月份差异: " + period.getMonths());
System.out.println("天数差异: " + period.getDays());
年份差异: 0
月份差异: 11
天数差异: 30

Duration 用来表示两个时间对象的时间间隔。

可以用于计算两个时间对象相差的天数、小时数、分数、秒数、纳秒数;支持 LocalTimeLocalDateTimeInstant等时间

LocalDateTime start = LocalDateTime.of(2025, 11, 10, 11, 11, 11);
LocalDateTime end = LocalDateTime.of(2025, 11, 11, 11, 11, 11);
// 1、得到Duration对象
Duration duration = Duration.between(start, end);
// 2、获取两个时间对象间隔的信息
System.out.println("间隔天: " + duration.toDays());
System.out.println("间隔小时: " + duration.toHours());
System.out.println("间隔分: " + duration.toMinutes());
System.out.println("间隔秒: " + duration.getSeconds());
System.out.println("间隔毫秒: " + duration.toMillis());
System.out.println("间隔纳秒: " + duration.toNanos());
间隔天: 1
间隔小时: 24
间隔分: 1440
间隔秒: 86400
间隔毫秒: 86400000
间隔纳秒: 86400000000000

zonedDateTime

时区时间

由于世界各个国家与地区的经度不同,各地区的时间也有所不同,因此会划分为不同的时区。每一个时区的时间也不太一样。

方法名说明
public static Set<String> getAvailableZoneIds()获取 Java 支持的全部时区 Id
public static ZoneId systemDefault()获取系统默认的时区
public static ZoneId of(String zoneId)把某个时区 id 封装成 ZoneId 对象
// 获取带时区的日期时间
ZonedDateTime zonedDateTime = currentDateTime.atZone(ZoneId.systemDefault());
System.out.println("带时区的日期和时间: " + zonedDateTime);// 转换时区
ZonedDateTime zonedDateTimeUTC = zonedDateTime.withZoneSameInstant(ZoneId.of("UTC"));
System.out.println("UTC时区的日期和时间: " + zonedDateTimeUTC);
带时区的日期和时间: 2024-09-05T11:54:48.556+08:00[Asia/Shanghai]
UTC时区的日期和时间: 2024-09-05T03:54:48.556Z[UTC]

Instant

Instant 是 Java 8 引入的 java.time 包中的一个类,用于表示时间线上的一个特定时刻。Instant 是一个精确到纳秒的时间表示,适用于需要高精度时间计算的场景。它简化了处理时间戳的复杂性,并提供了方便的 API 用于时间计算和比较。

  • 时间戳: Instant 表示自 1970-01-01T00:00:00Z(即 Unix 纪元时间)以来的时间点,以秒和纳秒的精度。
  • 不包含时区: Instant 只是一个时间点,不包含任何时区或日期信息。它只是一个绝对时间戳。
// 获取当前时间点
Instant now = Instant.now();
System.out.println("当前时间点: " + now);// 创建一个特定时间点
Instant specificTime = Instant.parse("2024-09-05T01:15:30Z");
System.out.println("特定时间点: " + specificTime);// 比较时间点
boolean isBefore = now.isBefore(specificTime);
System.out.println("现在是在特定时间点之前吗? " + isBefore);// 时间计算
Instant futureTime = now.plusSeconds(3600); // 增加一个小时
System.out.println("一小时以后: " + futureTime);
当前时间点: 2024-09-05T09:36:24.111Z
特定时间点: 2024-09-05T01:15:30Z
现在是在特定时间点之前吗? false
一小时以后: 2024-09-05T10:36:24.111Z

类型转换

// 转换为Date类型(如果需要与旧代码兼容)
Date oldStyleDate = Date.from(currentDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("转换为Date类型: " + oldStyleDate);// 转换为字符串与Date的相互转换(例如,从数据库读取或写入)
String dateString = oldStyleDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println("日期时间字符串: " + dateString);
转换为Date类型: Thu Sep 05 11:54:48 CST 2024
日期时间字符串: 2024-09-05T11:54:48.556

注意事项

在进行日期和时间操作时,注意时区的处理,特别是涉及跨时区操作时。使用 DateTimeFormatter 进行日期和时间的解析与格式化时,要确保使用的模式字符串与待处理的日期时间字符串相匹配。尽量避免使用旧版的日期和时间 API(如 java.util.Datejava.util.Calendar),新 API 更加易用且功能强大

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • c++ linux——进程共享内存
  • 《JavaEE进阶》----3.<SpringBoot项目创建细节大全+打jar包运行>
  • 若依框架登录鉴权详解(动态路由)
  • 鸿蒙轻内核M核源码分析系列四 中断Hwi
  • Spring Boot 整合 Sentinel 实现流量控制
  • LabVIEW与Python联合图像处理
  • 2024 年高教社杯全国大学生数学建模竞赛题目【A/B/C/D/E题】完整思路
  • TensorFlow-keras介绍(一)
  • 速盾:便宜的高防 CDN 推荐,高防 CDN 能抵御 DDoS 吗?
  • 探索 JavaScript 中的 instanceof 关键字
  • 3. GIS后端工程师岗位职责、技术要求和常见面试题
  • C语言新手小白详细教程(8)ASCll编码和字符串
  • macos下的 sed命令安装与使用 gnu-sed
  • 华为 HCIP-Datacom H12-821 题库 (10)
  • 损失函数与反向传播
  • [分享]iOS开发 - 实现UITableView Plain SectionView和table不停留一起滑动
  • 2017 年终总结 —— 在路上
  • GitUp, 你不可错过的秀外慧中的git工具
  • js ES6 求数组的交集,并集,还有差集
  • linux学习笔记
  • mongodb--安装和初步使用教程
  • Mysql5.6主从复制
  • OpenStack安装流程(juno版)- 添加网络服务(neutron)- controller节点
  • socket.io+express实现聊天室的思考(三)
  • SQLServer之创建数据库快照
  • vagrant 添加本地 box 安装 laravel homestead
  • Vue2 SSR 的优化之旅
  • 给第三方使用接口的 URL 签名实现
  • 猴子数据域名防封接口降低小说被封的风险
  • 浅谈Kotlin实战篇之自定义View图片圆角简单应用(一)
  • 如何使用 JavaScript 解析 URL
  • 微信小程序填坑清单
  •  一套莫尔斯电报听写、翻译系统
  • 用简单代码看卷积组块发展
  • 远离DoS攻击 Windows Server 2016发布DNS政策
  • ​ 轻量应用服务器:亚马逊云科技打造全球领先的云计算解决方案
  • ​​​​​​​ubuntu16.04 fastreid训练过程
  • ​软考-高级-信息系统项目管理师教程 第四版【第14章-项目沟通管理-思维导图】​
  • !$boo在php中什么意思,php前戏
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • $ git push -u origin master 推送到远程库出错
  • (12)Linux 常见的三种进程状态
  • (23)Linux的软硬连接
  • (Matalb时序预测)PSO-BP粒子群算法优化BP神经网络的多维时序回归预测
  • (二)换源+apt-get基础配置+搜狗拼音
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (三)uboot源码分析
  • (转)淘淘商城系列——使用Spring来管理Redis单机版和集群版
  • (转载)CentOS查看系统信息|CentOS查看命令
  • .net on S60 ---- Net60 1.1发布 支持VS2008以及新的特性
  • .NET Remoting学习笔记(三)信道
  • @SentinelResource详解
  • [ 常用工具篇 ] POC-bomber 漏洞检测工具安装及使用详解
  • [04]Web前端进阶—JS伪数组
  • [2]十道算法题【Java实现】