一、Instant
我们所处的时间点是在东八区,Java中Instant所计算出来的时间是按本初子午线的时间来算的,与我们的时间相差8个小时,也就是说当我的北京时间是上午九点时,本初子午线的时间是凌晨1点。

点击查看代码
@Test
public void test2(){
//now():获取本初子午线的标准时间
Instant instant = Instant.now();
System.out.println(instant);//返回的时间比北京时间晚八小时
System.out.println(\"===================\");
//添加时间偏移量
OffsetDateTime offset = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offset);
System.out.println(\"===================\");
//获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数
long milli = instant.toEpochMilli();
System.out.println(milli);
System.out.println(\"===================\");
//ofEpochMilli:通过给定的毫秒数,获取Instant实例 --->Date(long mills)
Instant instant1 = Instant.ofEpochMilli(1655370218862L);
System.out.println(instant1);
}
运行结果图
二、DateTimeFormatter
点击查看代码
@Test
public void test3(){
//实例化方式 自定义的格式:如ofPattern(\"yyyy-MM-dd hh:mm:ss\")
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd hh:mm:ss\");
//格式化
String s = formatter.format(LocalDateTime.now());
System.out.println(s);
//解析
TemporalAccessor parse = formatter.parse(\"2022-06-16 05:24:36\");
System.out.println(parse);
}
运行结果图
来源:https://www.cnblogs.com/twq46/p/16468625.html
本站部分图文来源于网络,如有侵权请联系删除。