Home > Back-end >  incompatible types: long cannot be converted to Instant
incompatible types: long cannot be converted to Instant

Time:04-16

I'm testing an example from here. But getting this error incompatible types: long cannot be converted to Instant .

Code:

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); 
        
        
    }
    
}

CodePudding user response:

This line

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

calculates the number of milliseconds between two times. Then it takes that number and tries to assign it to gap, which is of type Instant. In other words, you're taking a number, and trying to assign it to something which can only store a moment in time.

You should have declared gap as a long, not an Instant.

  • Related