概述
使用 LocalDate、LocalTime、LocalDateTime、Instant
LocalDate、LocalTime、LocalDateTime 类的实例是不可变的对象,分别表示使用 ISO-8601 日历系统(是国际化组织指定的现代公民日期和时间的表示方法)的日期、时间、日期和时间。它们提供了简单的日期或事件,并不包含当前的时间信息。也不包含与时区相关的信息。
// 1.LocalDate、LocalTime、LocalDateTime 使用方式相同
@Test
public void test1() {
LocalDateTime ldt1 = LocalDateTime.now();
// 可以指定时间偏移量,也就是时区
// OffsetDateTime odt = ldt1.atOffset(ZoneOffset.ofHours(8));
System.out.println(ldt1);
// 指定年月日时分秒
LocalDateTime ldt2 = LocalDateTime.of(2020, 10, 19, 13, 22, 33);
System.out.println(ldt2);
// 时间计算,所有的计算都返回一个新的实例
LocalDateTime ldt3 = ldt1.plusYears(2);
System.out.println(ldt3);
System.out.println(ldt1.getYear());
System.out.println(ldt1.getMonth());
System.out.println(ldt1.getDayOfWeek());
System.out.println(ldt1.getHour());
System.out.println(ldt1.getMinute());
System.out.println(ldt1.getSecond());
}
// 2. Instant:时间戳(以 Unix 元年:1970年1月1日 00:00:00 到某个时间之间的毫秒值
@Test
public void test2() {
Instant ins1 = Instant.now(); // 默认获取 UTC 时区
System.out.println(ins1);
// 设置间隔的时区,带有偏移量的时间
OffsetDateTime odt = ins1.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt);
/**
* 2020-02-10T04:50:54.879Z
* 2020-02-10T12:50:54.879+08:00
*/
// 转换成毫秒值
System.out.println(ins1.toEpochMilli());
// 设置指定秒数和时区的时间戳
Instant ins2 = Instant.ofEpochSecond(1000);
OffsetDateTime odt2 = ins2.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt2);
}
// 3.Duration:计算两个"时间"之间的间隔
// Period:计算两个"日期"之间的间隔
@Test
public void test3() {
Instant ins1 = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant ins2 = Instant.now();
Duration duration = Duration.between(ins1, ins2);
System.out.println(duration); // PT1.041S 也就是 1.041S
// 获取方式放在了 to/get 开头的方法中,为什么不统一?
System.out.println(duration.toMillis()); // 1041
System.out.println("----------------------------------------");
LocalTime lt1 = LocalTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime lt2 = LocalTime.now();
System.out.println(Duration.between(lt1, lt2).toMillis());
}
@Test
public void test4() {
LocalDate ld1 = LocalDate.of(2018, 8, 8) ;
LocalDate ld2 = LocalDate.now();
Period period = Period.between(ld1, ld2);
System.out.println(period); // P1Y6M2D 1年6月2天
System.out.println(period.getYears() + "年" + period.getMonths() + "月" + period.getDays() + "天");
}
最后
以上就是虚拟口红为你收集整理的java8 -- 新时间日期 API的全部内容,希望文章能够帮你解决java8 -- 新时间日期 API所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复