【高级编程】实用类详解(下)万字整理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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

服务器集群同步时间手记

1.时间服务器配置(必须root用户) (1)检查ntp是否安装 [root@node1 桌面]# rpm -qa|grep ntpntp-4.2.6p5-10.el6.centos.x86_64fontpackages-filesystem-1.41-1.1.el6.noarchntpdate-4.2.6p5-10.el6.centos.x86_64 (2)修改ntp配置文件 [r

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof