Java8时间类Instant及ZoneId,ZoneOffset用法

Instant.now().getEpochSecond()
时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
时间戳转化为Date或LocalDateTime时,需要添加ZoneId(地区)或ZoneOffset(偏移数据)来转为本地时间。

public static void main(String[] args) {

System.out.println(System.currentTimeMillis());
//1576405826436
System.out.println(LocalDateTime.now());
//2019-12-15T18:30:26.551
System.out.println(Instant.now().getEpochSecond());
//1576405826
System.out.println(Instant.now());
//2019-12-15T10:30:26.552Z
System.out.println(new Date().toInstant());
//2019-12-15T10:30:26.562Z

System.out.println(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
//1576406278199
System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toEpochSecond());
//1576405826
System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
//1576405826
System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
//1576405826563
System.out.println(LocalDateTime.now().atOffset(OffsetDateTime.now().getOffset()).toEpochSecond());
//1576405826
System.out.println(LocalDateTime.now().atOffset(OffsetDateTime.now().getOffset()).toInstant().getEpochSecond());
//1576405826
System.out.println(LocalDateTime.now().atOffset(OffsetDateTime.now().getOffset()).toInstant().toEpochMilli());
//1576405826564

	
Instant instant = Instant.now();

System.out.println(new Date(instant.getEpochSecond()*1000));
//Sun Dec 15 18:46:54 CST 2019
System.out.println(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
//2019-12-15T18:46:54.303
}

你可能感兴趣的:(Java,1024程序员节)