java.time包中的类如何使用
2024/1/4 1:32:44
本文主要是介绍java.time包中的类如何使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
java.time包是在java8中引入的日期和时间处理API,提供了一组全新的类,用于更灵活、更强大的处理日期和时间。
常用用法
1、localDate
表示日期,不包含时间和时区信息
import java.time.LocalDate; public class LocalDateExample { public static void main(String[] args) { // 获取当前日期 LocalDate currentDate = LocalDate.now(); System.out.println("Current Date: " + currentDate); // 创建指定日期 LocalDate specificDate = LocalDate.of(2022, 1, 1); System.out.println("Specific Date: " + specificDate); // 执行日期操作 LocalDate futureDate = currentDate.plusMonths(3); System.out.println("Future Date: " + futureDate); } }
2、loaclTime
表示时间,不包含日期和时区信息
import java.time.LocalTime; public class LocalTimeExample { public static void main(String[] args) { // 获取当前时间 LocalTime currentTime = LocalTime.now(); System.out.println("Current Time: " + currentTime); // 创建指定时间 LocalTime specificTime = LocalTime.of(12, 30, 45); System.out.println("Specific Time: " + specificTime); // 执行时间操作 LocalTime futureTime = currentTime.plusHours(2); System.out.println("Future Time: " + futureTime); } }
3、LocalDateTime
表示日期和时间,不包含时区信息
import java.time.LocalDateTime; public class LocalDateTimeExample { public static void main(String[] args) { // 获取当前日期和时间 LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("Current Date and Time: " + currentDateTime); // 创建指定日期和时间 LocalDateTime specificDateTime = LocalDateTime.of(2022, 1, 1, 12, 30); System.out.println("Specific Date and Time: " + specificDateTime); // 执行日期和时间操作 LocalDateTime futureDateTime = currentDateTime.plusDays(7).minusHours(3); System.out.println("Future Date and Time: " + futureDateTime); } }
4、ZoneDateTime
表示带有时区的日期和时间
import java.time.ZonedDateTime; import java.time.ZoneId; public class ZonedDateTimeExample { public static void main(String[] args) { // 获取带有时区信息的当前日期和时间 ZonedDateTime currentZonedDateTime = ZonedDateTime.now(); System.out.println("Current Date and Time with Zone: " + currentZonedDateTime); // 创建指定时区的日期和时间 ZonedDateTime specificZonedDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("America/New_York")); System.out.println("Specific Date and Time with Zone: " + specificZonedDateTime); } }
这篇关于java.time包中的类如何使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-0601-电商商品中心解密:仅凭SKU真的足够吗?
- 2024-05-01为什么公共事业机构会偏爱 TiDB :TiDB 数据库在某省妇幼健康管理系统的应用
- 2024-04-26敏捷开发:想要快速交付就必须舍弃产品质量?
- 2024-04-26静态代码分析的这些好处,我竟然都不知道?
- 2024-04-26你在测试金字塔的哪一层?(下)
- 2024-04-26快刀斩乱麻,DevOps让代码评审也自动起来
- 2024-04-262024年最好用的10款ER图神器!
- 2024-04-2203-为啥大模型LLM还没能完全替代你?
- 2024-04-2101-大语言模型发展
- 2024-04-17基于SpringWeb MultipartFile文件上传、下载功能