javadatelocaldatetemporal

ClassCastException: java.util.Date cannot be cast to java.time.temporal.Temporal


I am trying to work out the number of days between two dates. I am getting an error when I run the code: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Date cannot be cast to java.time.temporal.Temporal

Here is my code:

ServiceJpaController serController = new ServiceJpaController(emf);
    List<Service> serviceList = serController.findServiceEntities();
    LocalDate today = LocalDate.now();
    System.out.println("Today date: "+ today); 
    for(Service service:serviceList){
        Date lastServiced = service.getDateOfService();
        System.out.println("Serviced date: "+ lastServiced); 
        long daysBetween = Duration.between(lastServiced.toInstant(), today).toDays();
        if(daysBetween >= 90){
            jTxtAreaServiceDate.append(service.toString());
        }}

The print statements were added just to check if the variables contained the dates, which they do. The output window showed:

Today date: 2022-08-03

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Date cannot be cast to java.time.temporal.Temporal

Serviced date: Sun May 08 00:00:00 BST 2022

I've had a look for a solution but so far have been unable to find anything. If anyone could explain what the error means and how I could go about solving my problem I would be most grateful.


Solution

  • I think the best thing you can do is to see if you can get LocalDate for the code Date lastServiced = service.getDateOfService(); which means returning LocalDate from method service.getDateOfService();

    Sometimes it is probably not in your control. Therefore you can try the next best solution, which is to convert Util.Date to a LocalDate. You can use the below code for that.

    LocalDate lastServiceLocalDate = lastServiced.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
    

    Now you have both LocalDate so you can use the below code to get days between

    long daysBetween = DAYS.between(lastServiceLocalDate, today);