java.time常用方法汇总

简介: `java.time` API 是从 Java 8 开始引入的时间日期处理库,旨在替代老旧的 `java.util.Date` 和 `Calendar`。它提供了更简洁、强大和灵活的方式处理日期、时间、时区及时间间隔,支持全球化和时间计算需求。API 包含获取当前时间、创建指定时间、解析和格式化字符串、进行加减运算、比较时间、获取年月日时分秒、计算时间间隔、时区转换以及判断闰年等功能。示例代码展示了如何使用这些功能,极大简化了开发中的时间处理任务。

java.time API 介绍

java.timeAPI 是从 Java 8 开始引入的一套强大的时间日期处理库,旨在替代老旧的 java.util.Datejava.util.Calendar。该 API 以更简洁、强大和灵活的方式处理日期、时间、时区以及时间间隔,适合各种全球化和时间计算的需求。

1.获取当前日期、时间、日期时间

提供了获取当前系统时间的多种方式,包括不含时间的日期、不含日期的时间、完整的日期时间,以及带时区的日期时间。

ini

代码解读

复制代码

// LocalDate: 获取当前日期(不含时间)
LocalDate currentDate = LocalDate.now();

// LocalTime: 获取当前时间(不含日期)
LocalTime currentTime = LocalTime.now();

// LocalDateTime: 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();

// ZonedDateTime: 获取带时区的当前日期和时间
ZonedDateTime currentZonedDateTime = ZonedDateTime.now();

// Instant: 获取当前的瞬时时间点(用于时间戳)
Instant currentInstant = Instant.now();
2.创建指定的日期、时间、日期时间

根据需求创建指定的日期、时间、带时区的日期时间,甚至可以直接通过时间戳生成时间点。日期必须对年份和月份有效,否则将引发DateTimeException异常。

ini

代码解读

复制代码

// LocalDate: 创建指定的日期
LocalDate date = LocalDate.of(2024, 9, 23);  // 年, 月, 日

// LocalTime: 创建指定的时间
LocalTime time = LocalTime.of(14, 30, 0);    // 时, 分, 秒

// LocalDateTime: 创建指定的日期和时间
LocalDateTime dateTime = LocalDateTime.of(2024, 9, 23, 14, 30); // 年, 月, 日, 时, 分

// ZonedDateTime: 创建指定时区的日期和时间
ZonedDateTime zonedDateTime = ZonedDateTime.of(2024, 9, 23, 14, 30, 0, 0, ZoneId.of("Asia/Shanghai"));

// ZoneId: 获取指定时区
ZoneId zoneId = ZoneId.of("America/New_York");

// Instant: 创建指定的时间点
Instant instant = Instant.ofEpochSecond(1609459200L); // 秒级时间戳
3.解析字符串为日期、时间、日期时间

java.time 提供了从字符串解析日期、时间的能力,支持标准格式和自定义格式,非常适合从文本或文件中读取时间信息。

ini

代码解读

复制代码

// LocalDate: 从字符串解析日期
LocalDate parsedDate = LocalDate.parse("2024-09-23");

// LocalTime: 从字符串解析时间
LocalTime parsedTime = LocalTime.parse("14:30:00");

// LocalDateTime: 从字符串解析日期和时间
LocalDateTime parsedDateTime = LocalDateTime.parse("2024-09-23T14:30:00");

// DateTimeFormatter: 使用自定义格式解析日期时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime formattedDateTime = LocalDateTime.parse("2024-09-23 14:30:00", formatter);
4.格式化日期、时间、日期时间为字符串

ini

代码解读

复制代码

// LocalDate: 格式化日期为字符串
String dateString = currentDate.format(DateTimeFormatter.ISO_DATE); // 输出格式: 2024-09-23

// LocalTime: 格式化时间为字符串
String timeString = currentTime.format(DateTimeFormatter.ISO_TIME); // 输出格式: 14:30:00

// LocalDateTime: 格式化日期和时间为字符串
String dateTimeString = currentDateTime.format(DateTimeFormatter.ISO_DATE_TIME); // 输出格式: 2024-09-23T14:30:00

// DateTimeFormatter: 使用自定义格式
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedString = currentDateTime.format(customFormatter); // 输出格式: 2024-09-23 14:30:00  
5.日期、时间的加减运算

ini

代码解读

复制代码

// LocalDate: 增加或减少日期
LocalDate newDate = currentDate.plusDays(5);   // 增加5天
LocalDate earlierDate = currentDate.minusMonths(2); // 减少2个月

// LocalTime: 增加或减少时间
LocalTime newTime = currentTime.plusHours(2);  // 增加2小时
LocalTime earlierTime = currentTime.minusMinutes(30); // 减少30分钟

// LocalDateTime: 增加或减少日期时间
LocalDateTime newDateTime = currentDateTime.plusWeeks(1); // 增加1周
LocalDateTime earlierDateTime = currentDateTime.minusDays(3); // 减少3天

// ZonedDateTime: 带时区的加减
ZonedDateTime newZonedDateTime = currentZonedDateTime.plusYears(1); // 增加1年
ZonedDateTime earlierZonedDateTime = currentZonedDateTime.minusHours(6); // 减少6小时

// Instant: 增加或减少秒数
Instant newInstant = currentInstant.plusSeconds(3600); // 增加1小时(3600秒)
6.日期、时间的比较

ini

代码解读

复制代码

// LocalDate: 比较日期
boolean isBefore = currentDate.isBefore(LocalDate.of(2025, 1, 1)); // 判断当前日期是否在2025-01-01之前
boolean isAfter = currentDate.isAfter(LocalDate.of(2020, 1, 1));   // 判断当前日期是否在2020-01-01之后

// LocalTime: 比较时间
boolean isEarlier = currentTime.isBefore(LocalTime.of(16, 0)); // 判断当前时间是否在16:00之前

// LocalDateTime: 比较日期时间
boolean isLater = currentDateTime.isAfter(LocalDateTime.of(2023, 9, 23, 12, 0)); // 判断当前时间是否在给定时间之后

// ZonedDateTime: 比较带时区的日期时间
boolean zonedIsBefore = currentZonedDateTime.isBefore(ZonedDateTime.of(2024, 9, 23, 12, 0, 0, 0, ZoneId.of("Asia/Shanghai")));
7.获取年、月、日、时、分、秒

获取日期有关的值。

ini

代码解读

复制代码

// LocalDate: 获取年、月、日
int year = currentDate.getYear();
int month = currentDate.getMonthValue();
int day = currentDate.getDayOfMonth();

// LocalTime: 获取时、分、秒
int hour = currentTime.getHour();
int minute = currentTime.getMinute();
int second = currentTime.getSecond();

// LocalDateTime: 获取年、月、日、时、分、秒
int dateTimeYear = currentDateTime.getYear();
int dateTimeMonth = currentDateTime.getMonthValue();
int dateTimeDay = currentDateTime.getDayOfMonth();
int dateTimeHour = currentDateTime.getHour();
int dateTimeMinute = currentDateTime.getMinute();
int dateTimeSecond = currentDateTime.getSecond();

// ZonedDateTime: 获取年、月、日、时、分、秒、时区
ZoneId zone = currentZonedDateTime.getZone();
8.计算时间间隔

ini

代码解读

复制代码

// Period: 计算两个日期之间的年、月、日差异
Period period = Period.between(LocalDate.of(2020, 1, 1), LocalDate.of(2024, 9, 23));
int yearsBetween = period.getYears();
int monthsBetween = period.getMonths();
int daysBetween = period.getDays();

// Duration: 计算两个时间或日期时间之间的时、分、秒差异
Duration duration = Duration.between(LocalTime.of(14, 0), LocalTime.of(16, 30));
long hoursBetween = duration.toHours();   // 获取小时差
long minutesBetween = duration.toMinutes(); // 获取分钟差
9.时区相关操作

ini

代码解读

复制代码

// ZoneId: 获取时区
ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
ZoneId newYorkZone = ZoneId.of("America/New_York");

// ZonedDateTime: 转换时区,保持相同瞬时时间
ZonedDateTime newYorkTime = currentZonedDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));

// 获取所有可用的时区ID
Set<String> allZoneIds = ZoneId.getAvailableZoneIds();
10.判断闰年

ini

代码解读

复制代码

// LocalDate: 判断是否是闰年
boolean isLeapYear = currentDate.isLeapYear();


转载来源:https://juejin.cn/post/7417717379071082548

相关文章
|
8天前
|
机器学习/深度学习 人工智能 自然语言处理
PAI Model Gallery 支持云上一键部署 DeepSeek-V3、DeepSeek-R1 系列模型
DeepSeek 系列模型以其卓越性能在全球范围内备受瞩目,多次评测中表现优异,性能接近甚至超越国际顶尖闭源模型(如OpenAI的GPT-4、Claude-3.5-Sonnet等)。企业用户和开发者可使用 PAI 平台一键部署 DeepSeek 系列模型,实现 DeepSeek 系列模型与现有业务的高效融合。
|
8天前
|
人工智能 搜索推荐 Docker
手把手教你使用 Ollama 和 LobeChat 快速本地部署 DeepSeek R1 模型,创建个性化 AI 助手
DeepSeek R1 + LobeChat + Ollama:快速本地部署模型,创建个性化 AI 助手
2802 112
手把手教你使用 Ollama 和 LobeChat 快速本地部署 DeepSeek R1 模型,创建个性化 AI 助手
|
3天前
|
云安全 边缘计算 人工智能
对话|ESA如何助力企业高效安全开展在线业务?
ESA如何助力企业安全开展在线业务
1022 8
|
7天前
|
API 开发工具 Python
阿里云PAI部署DeepSeek及调用
本文介绍如何在阿里云PAI EAS上部署DeepSeek模型,涵盖7B模型的部署、SDK和API调用。7B模型只需一张A10显卡,部署时间约10分钟。文章详细展示了模型信息查看、在线调试及通过OpenAI SDK和Python Requests进行调用的步骤,并附有测试结果和参考文档链接。
1530 9
阿里云PAI部署DeepSeek及调用
|
6天前
|
人工智能 自然语言处理 JavaScript
宜搭上新,DeepSeek 插件来了!
钉钉宜搭近日上线了DeepSeek插件,无需编写复杂代码,普通用户也能轻松调用强大的AI大模型能力。安装后,平台新增「AI生成」组件,支持创意内容生成、JS代码编译、工作汇报等场景,大幅提升工作效率。快来体验这一高效智能的办公方式吧!
1417 6
|
3天前
|
人工智能 自然语言处理 API
DeepSeek全尺寸模型上线阿里云百炼!
阿里云百炼平台近日上线了DeepSeek-V3、DeepSeek-R1及其蒸馏版本等六款全尺寸AI模型,参数量达671B,提供高达100万免费tokens。这些模型在数学、代码、自然语言推理等任务上表现出色,支持灵活调用和经济高效的解决方案,助力开发者和企业加速创新与数字化转型。示例代码展示了如何通过API使用DeepSeek-R1模型进行推理,用户可轻松获取思考过程和最终答案。
|
15天前
|
Linux iOS开发 MacOS
deepseek部署的详细步骤和方法,基于Ollama获取顶级推理能力!
DeepSeek基于Ollama部署教程,助你免费获取顶级推理能力。首先访问ollama.com下载并安装适用于macOS、Linux或Windows的Ollama版本。运行Ollama后,在官网搜索“deepseek”,选择适合你电脑配置的模型大小(如1.5b、7b等)。通过终端命令(如ollama run deepseek-r1:1.5b)启动模型,等待下载完成即可开始使用。退出模型时输入/bye。详细步骤如下图所示,轻松打造你的最强大脑。
9565 86
|
1月前
|
供应链 监控 安全
对话|企业如何构建更完善的容器供应链安全防护体系
阿里云与企业共筑容器供应链安全
171379 18
|
7天前
|
缓存 自然语言处理 安全
快速调用 Deepseek API!【超详细教程】
Deepseek 强大的功能,在本教程中,将指导您如何获取 DeepSeek API 密钥,并演示如何使用该密钥调用 DeepSeek API 以进行调试。
|
4天前
|
人工智能 数据可视化 Linux
【保姆级教程】3步搞定DeepSeek本地部署
DeepSeek在2025年春节期间突然爆火出圈。在目前DeepSeek的网站中,极不稳定,总是服务器繁忙,这时候本地部署就可以有效规避问题。本文以最浅显易懂的方式带读者一起完成DeepSeek-r1大模型的本地部署。