Someone knows why the Java IDE returns an error when I convert from String to GregorianCalendar

2
   BufferedReader br = new BufferedReader (new InputStreamReader (System.in));

    String fechaN;
    System.out.println("Introduce tu fecha de nacimiento en el siguiento formato dd/mm/aaaa");
        try{    
            fechaN = br.readLine();
            SimpleDateFormat sdf = new SimpleDateFormat ("dd/MM/yyyy");
            Date d = sdf.parse(fechaN); 
            Calendar fecha = new GregorianCalendar ();
            fecha.setTime(d);
            if(fecha.get(fecha.MONTH) == fecha.JANUARY){
                System.out.println("El mes que escribiste fue Enero");
            }else{
                System.out.println("Es un mes distinto al que buscamos");
            }

        }catch(IOException ioe){
            System.out.println("Error al leer datos");
        }

The problem lies in the code "Date d = sdf.parse (dateN)" the parameter itself requests an object of type Date but I have seen that many make the change of String to date format in this way. The IDE logically tells me to cast it to Date Type "Date d = (Date) sdf.parse (dateN);" but then when I execute it it throws me an error of ClassCastException. I hope you can help me.

    
asked by Ronald Sanchez 11.04.2017 в 20:10
source

3 answers

2

Check in your import , if the import of your date is not in java.sql.Date , if so, that is the error , you grab a class that is not, it should be java.util.Date .

    
answered by 11.04.2017 / 20:39
source
1

The parse(String string) method in fact returns a result of type Date , so if you get a ClassCastException , check if you imported the class Date that corresponds:

There are two classes Date .

  • java.util.Date and
  • java.sql.Date

Check your imports, it is very likely that you imported java.sql.Date , so the cast of java.util.Date to subclass java.sql.Date fails you with a ClassCastException . If so, change the import to java.util.Date and your problem is resolved.

    
answered by 11.04.2017 в 20:40
0

example

try {
        String date = "11/12/1999";
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Date fechaSalida = format.parse(date);
        System.out.println(fechaSalida);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
    }

I hope it serves you!

    
answered by 11.04.2017 в 20:17