时间差计算

199 阅读1分钟

一般在java中,要计算两个时间差,除了时间戳相减这种,我们还可以在jdk8以上版本采用这种

public class TimeDemo {

    public static void main(String[] args) {
        Instant start = Instant.now();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);        }
        Instant end = Instant.now();

        Duration duration = Duration.between(start, end);
        System.out.println("时间差:" + duration.toMillis());
    }
}

如果是LocalDateTime转Instant,可以使用以下方法转

import java.time.Instant;  
import java.time.LocalDateTime;  
import java.time.ZoneId;  
  
public class LocalDateTimeDemo {  
  
public static void main(String[] args) {  
Instant localDateTimeToInstant = LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant();  
  
}  
}

Instant转LocalDateTime


import java.time.Instant;  
import java.time.LocalDateTime;  
import java.time.ZoneId;  
  
public class LocalDateTime1Demo {  
  
public static void main(String[] args) {  
ZoneId zone = ZoneId.systemDefault();  
Instant instant = Instant.now();  
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);  
System.out.println(localDateTime);  
}  
  
}