关于时间API一些使用的记载。
时间API
获取时间戳
System.currentTimeMillis() 和 Instant.now()
@Test
public void test() {
// 时间戳 以Unix 元年,1907年1月1日 00:00:00 到某个时间之间的毫秒值
long time = System.currentTimeMillis();
// 默认获取UTC 时区
Instant instant = Instant.now();
// 通过偏移时区获取北京时间所在时区的时间
OffsetDateTime odt = instant.atOffset(ZoneOffset.ofHours(8));
long time2 = odt.toInstant().toEpochMilli();
System.out.println("time = " + time);
System.out.println("time2 = " + time2);
}
结果:
// 输出结果:当前时间戳 = 1649864850714
获取当前时间
LocalTime、LocalDate 和 LocalDateTime
@Test
public void test2() {
// 获取当前时间
LocalDateTime ldt = LocalDateTime.now();
System.out.println("ldt = " + ldt);
// 获取年、月、日等
int year = ldt.getYear();
// 通过Month对象,获取对象里的value
int month = ldt.getMonth().getValue();
// 等同于下面的获取month方式
int month1 = ldt.getMonthValue();
int day = ldt.getDayOfMonth();
System.out.println("year = " + year);
System.out.println("month = " + month);
System.out.println("month1 = " + month1);
System.out.println("day = " + day);
System.out.println("-----------------------------");
// 时间加减
System.out.println("ldt.plusYears(2) = " + ldt.plusYears(2));
System.out.println("ldt.minusYears(3) = " + ldt.minusYears(3));
// 通过LocalDateTime构造时间
LocalDateTime time1 = LocalDateTime.of(2022, 07, 31, 21, 20, 20);
System.out.println("time1 = " + time1);
// 时间格式化
String s = ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println("格式化后的时间 = " + s);
}
时间日期的计算
Duration 和 Period
// Duration: 计算两个“时间”之间的间隔
// Period: 计算两个“日期”之间的间隔
@Test
public void test3() throws InterruptedException {
Instant ins1 = Instant.now();
Thread.sleep(1000);
Instant ins2 = Instant.now();
System.out.println("ins秒-------" + Duration.between(ins1, ins2).toMillis());
System.out.println("--------------------------");
LocalTime lt1 = LocalTime.now();
Thread.sleep(1000);
LocalTime lt2 = LocalTime.now();
System.out.println("lt秒-------" + Duration.between(lt1, lt2).toMillis());
LocalDate ld1 = LocalDate.of(2021, 8, 1);
Thread.sleep(1000);
LocalDate ld2 = LocalDate.now();
System.out.println("两个日期相差-------年" + Period.between(ld1, ld2).getYears());
System.out.println("两个日期相差-------月" + Period.between(ld1, ld2).getMonths());
System.out.println("两个日期相差-------日" + Period.between(ld1, ld2).getDays());
}
时间矫正器
TemporalAdjusters
// 时间矫正器 TemporalAdjusters
@Test
public void test4() {
LocalDateTime ldt = LocalDateTime.now();
System.out.println("ldt = " + ldt);
// 将时间调整到周日
LocalDateTime ldt2 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println("ldt2 = " + ldt2);
// 自定义:下一个工作日
LocalDateTime ldt4 = ldt.with(l -> {
LocalDateTime ldt3 = (LocalDateTime) l;
DayOfWeek dow = ldt.getDayOfWeek();
if (dow.equals(DayOfWeek.FRIDAY)) {
return ldt3.plusDays(3);
} else if (dow.equals(DayOfWeek.SATURDAY)) {
return ldt3.plusDays(2);
} else {
return ldt3.plusDays(1);
}
});
System.out.println("ldt4 = " + ldt4);
}
可以看看我的学习——个人博客:
网站:https://www.fuzm.wang/
—————————————————————————
作为初学者,很多知识都没有掌握,见谅,如有错误请指出,以期进步,感谢!。后续有新的学习,继续补充上来。