java8中时间API怎么用
一、介绍
Java8中的时间API是基于Joda-Time库的升级版本,主要提供了一系列的新的日期和时间的API,使得Java开发者能够更加方便、快捷的处理日期和时间相关的操作。新的时间API的设计受到了Joda-Time库的启发,同时也加入了一些新的特性,使得Java8中的时间API更加强大、灵活。
二、时间API的主要类
Java8中的时间API主要包括以下几个类:
- LocalDate:表示一个确切的日期,比如2014-03-11;
- LocalTime:表示一个确切的时间,比如10:15:30;
- LocalDateTime:表示一个确切的日期和时间,比如2014-03-11 10:15:30;
- ZonedDateTime:表示一个确切的日期和时间,并带有时区信息,比如2014-03-11 10:15:30 Asia/Shanghai;
- Instant:表示一个时间点,比如2014-03-11 10:15:30.000,精确到毫秒;
- Duration:表示一段时间,比如2小时5分钟;
- Period:表示一段时间,比如2年3月4天;
- ZoneId:表示一个时区,比如Asia/Shanghai;
- ZoneOffset:表示一个时区的偏移量,比如+08:00;
三、使用示例
下面是一个使用Java8中的时间API的示例:
public class DateTimeTest {
public static void main(String[] args) {
// 获取当前的日期时间
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("date1: " + date1);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("月: " + month +", 日: " + day +", 秒: " + seconds);
LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
System.out.println("date2: " + date2);
// 12 december 2014
LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
System.out.println("date3: " + date3);
// 22 小时 15 分钟
LocalTime date4 = LocalTime.of(22, 15);
System.out.println("date4: " + date4);
// 解析字符串
LocalTime date5 = LocalTime.parse("20:15:30");
System.out.println("date5: " + date5);
}
}
猜您想看
-
Disruptor的原理是什么
Disrupt...
2023年07月23日 -
nacos NamingProxy中getServiceList的原理及用法
1.Namin...
2023年05月26日 -
java怎么在给定的数组里面寻找重复数
寻找重复数是指...
2023年07月20日 -
如何设置Windows提示音效果
Windows...
2023年05月12日 -
Python中怎么远程获取回收站内容
使用Pytho...
2023年07月22日 -
win系统磁盘0磁盘分区1指的是什么意思
Win系统磁盘...
2023年07月22日