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

2024-09-05 19:44

本文主要是介绍【高级编程】实用类详解(下)万字整理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 更加易用且功能强大

这篇关于【高级编程】实用类详解(下)万字整理Java时间日期类 JDK8新日期的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1139892

相关文章

Java Stream流与使用操作指南

《JavaStream流与使用操作指南》Stream不是数据结构,而是一种高级的数据处理工具,允许你以声明式的方式处理数据集合,类似于SQL语句操作数据库,本文给大家介绍JavaStream流与使用... 目录一、什么是stream流二、创建stream流1.单列集合创建stream流2.双列集合创建str

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——