不兼容的类型:long 无法转换为 Instant

incompatible types: long cannot be converted to Instant

我正在测试来自 here 的示例。但是得到这个错误 incompatible types: long cannot be converted to Instant .

代码:

import java.time.Instant;
import java.time.temporal.Temporal;
import java.time.temporal.ChronoUnit;


class HelloWorld {
    

    public static void main(String[] args) {
    
    Instant previous = Instant.parse("2022-04-16T08:03:50.054341Z"), current, gap;
    
    
        current = Instant.now();
        if (previous != null) {
            gap = ChronoUnit.MILLIS.between(previous,current);
        }
        
        System.out.println("Hello, World! "+current+ " , "+previous + " , "+gap); 
        
        
    }
    
}

这一行

gap = ChronoUnit.MILLIS.between(previous,current);

计算两次之间的毫秒数。然后它获取该数字并尝试将其分配给类型为 Instantgap。换句话说,您正在获取一个数字,并试图将其分配给只能及时存储片刻的东西。

您应该将 gap 声明为 long,而不是 Instant