Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

incompatible types: long cannot be converted to Instant

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading