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); } }
本文作者:TranquilTimber
本文链接:https://www.cnblogs.com/gbrr/p/17943389
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2023-01-03 Android学习day03【跑马灯】