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

[Java 基础]日期时间

日期时间相关功能建议使用 Java 8 引入的 java.time 包,这是一个更加现代化、易用且功能强大的日期时间 API。同时,我们也会简要提及旧的 java.util.Datejava.util.Calendar 类,因为你可能会在遗留代码中遇到它们。

早期 Java 日期时间 API (<u>java.util.Date</u><u>java.util.Calendar)

在 Java 8 之前,主要的日期和时间处理类是 java.util.Datejava.util.Calendar。然而,Date 类是 Java 中用于表示日期和时间的基础类,位于 java.util 包中。它提供了处理日期和时间的基本功能,但在 Java 8 之后,更推荐使用 java.time 包中的新日期时间 API(如 LocalDate、LocalDateTime 等)。

Date

可以通过如下的方式来创建 Date 对象:

import java.util.Date;// 当前日期和时间
Date now = new Date();
System.out.println("当前时间: " + now);// 指定毫秒数创建Date (从1970-01-01 00:00:00 GMT开始计算)
Date specificDate = new Date(1640995200000L); // 2022-12-31 00:00:00
System.out.println("特定时间: " + specificDate);

Date 常用的方法也就只有这几个:

Date date = new Date();// 获取时间戳(自1970年以来的毫秒数)
long timestamp = date.getTime();
System.out.println("时间戳: " + timestamp);// 设置时间(通过毫秒数)
date.setTime(1640995200000L);// 比较两个日期
Date anotherDate = new Date();
System.out.println("比较结果: " + date.compareTo(anotherDate));
System.out.println("是否在此之前: " + date.before(anotherDate));
System.out.println("是否在此之后: " + date.after(anotherDate));

使用 SimpleDateFormat 类来将 Date 对象格式化为指定格式的日期字符串:

import java.text.SimpleDateFormat;Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String formattedDate = sdf.format(date);
System.out.println("格式化后的日期: " + formattedDate);// 解析字符串为Date
try {Date parsedDate = sdf.parse("2023-01-01 12:00:00");System.out.println("解析后的日期: " + parsedDate);
} catch (Exception e) {e.printStackTrace();
}

:::color3
Date 有很多的局限性,SimpleDateFormat 不是线程安全的,它的年份从1900 年开始计算,月份从 0 开始,时区处理不够直观,Date 对象是可变的(可以通过setTime修改),更推荐使用 Java 8 引入了 java.time 包中提供的日期时间处理类

:::

LocalDateTime

LocalDateTime 类表示一个包含日期和时间的本地日期时间,例如 2023-10-26T10:30:45

可以通过如下的方式来创建 LocalDateTime 对象:

LocalDateTime nowDateTime = LocalDateTime.now(); // 获取当前日期和时间
LocalDateTime specificDateTime = LocalDateTime.of(2024, Month.FEBRUARY, 20, 16, 0); // 指定年月日时分
LocalDateTime fromDateAndTime = LocalDateTime.of(LocalDate.now(), LocalTime.now()); // 从 LocalDate 和 LocalTime 合并
LocalDateTime parsedDateTime = LocalDateTime.parse("2023-12-25T12:00:00"); // 从字符串解析

LocalDateTime 和时间字符串的相互转换:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;// 当前日期时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前时间: " + now);// 格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = now.format(formatter);
System.out.println("格式化: " + formatted);// 解析
LocalDateTime parsed = LocalDateTime.parse("2023-01-01 12:00:00", formatter);
System.out.println("解析: " + parsed);

从 LocalDateTime 获取日期和时间信息,可以分别使用 getYear(), getMonth(), getDayOfMonth(), getHour(), getMinute(), getSecond() 等方法。

对 LocalDateTime 进行时间的操作,可以使用 plusDays(), minusHours(), withMonth() 等方法,与 LocalDate 和 LocalTime 类似。

对 LocalDateTime 进行时间的比较,可以使用 isAfter(), isBefore(), isEqual() 等方法。

LocalDateTime 可以与 Date 进行相互的转换:

import java.time.Instant;
import java.time.ZoneId;// Date 转 LocalDateTime
Date oldDate = new Date();
LocalDateTime newDate = oldDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();// LocalDateTime 转 Date
LocalDateTime now = LocalDateTime.now();
Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

ZonedDateTime

ZonedDateTime 类表示一个带有时区的日期和时间,例如 2023-10-26T10:30:45+08:00[Asia/Shanghai]。

有如下几种方式创建 ZonedDateTime 对象:

ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
ZonedDateTime zonedNow = ZonedDateTime.now(shanghaiZone); // 获取指定时区的当前日期和时间
LocalDateTime localDateTime = LocalDateTime.of(2024, 3, 10, 9, 0);
ZonedDateTime zonedSpecific = ZonedDateTime.of(localDateTime, shanghaiZone);
ZonedDateTime parsedZoned = ZonedDateTime.parse("2023-11-15T18:00:00+09:00[Asia/Tokyo]");

获取时区信息:

ZoneId zoneId = zonedNow.getZone();

时区转换:

ZoneId newYorkZone = ZoneId.of("America/New_York");
ZonedDateTime newYorkTime = zonedNow.withZoneSameInstant(newYorkZone);

ZonedDateTime 也可以格式化为指定格式的时间字符串:

// 获取当前带时区的日期时间
ZonedDateTime zonedDateTime = ZonedDateTime.now();// 定义格式化模式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");// 格式化
String formattedDateTime = zonedDateTime.format(formatter);System.out.println("格式化后的时间: " + formattedDateTime);
http://www.xdnf.cn/news/1052299.html

相关文章:

  • 力扣的SQL
  • Spring AI 对话记忆持久化实战-MySQL方案
  • 【分析学】 从确界定理出发——实数系完备定理
  • Proteus8.17仿真51单片机驱动ST7920 LCD12864
  • MyBatisPlus 全面学习路径
  • 《仿盒马》app开发技术分享-- 回收金提现记录查询(端云一体)
  • java 集合 泛型
  • 第2讲、LangChain应用架构与核心组件:构建LLM应用的基石
  • 访问网页的全过程
  • 电脑端应用使用统计工具,精准分析你的习惯
  • wordpress外贸独立站搭建步骤
  • Appium框架下载时卡主的解决办法(ERR_TLS_CERT_ALTNAME_INVALID)
  • kicad运行时出错,_Pnext->_Myproxy = nullptr;访问内存出错解决措施
  • 华为OD机试_2025 B卷_磁盘容量排序(Python,100分)(附详细解题思路)
  • 互联网大厂Java求职面试:AI与大模型技术在电商系统中的架构设计与性能优化
  • ​​信息系统项目管理师-项目整合管理 知识点总结与例题分析​​
  • C++多线程与并发中线程池设计、锁优化
  • Linux入门(十八)read函数
  • 第十六届蓝桥杯国赛(2025)C/C++B组 蓝桥星数字 独家解析
  • Python 基础语法 (4)【适合0基础】
  • 幻休 v3.0.02 | AI趣味呼吸 助眠音乐 冥想音频
  • Java微服务框架技术选型全景报告
  • LangGraph--Agent常见的模式2(并行、数据路由)
  • 链表(C语言)—学习笔记
  • 淘宝/天猫API系列-商品列表页采集接口教程
  • win10 乌班图系统安装(推荐)
  • 安装前端vite框架,后端安装fastapi框架
  • 第二十章 Centos8的使用
  • 苏州SAP代理商:哲讯科技助力企业数字化转型
  • CSS 第四天 复合选择器、CSS特性、背景属性、显示模式