Search code examples
javaapache-poidateformatter

date format is not correct java


I'm trying to read a date cell from excel file, i'm using DataFormatter but the problem is that the format that i get is not correct (day and month are inverted), example: in the excel file: 15/03/2018 After reading: 03/15/2018

I need to fix this or convert the cell to string format in order to compare it with another string.

thanks in advance.

This is how i read the cell:

DataFormatter formatter = new DataFormatter();
String current_date = formatter.formatCellValue(date_cell);

Solution

  • Try something like this:

    String s = "03/15/2018";    
    Date d = new Date(s);   
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    String t = df.format(d);
    System.out.println(t);
    

    (s corresponds to your current_date variable and follows directly after your other code)

    NB: you have to use capital Ms because in date/time formats 'm' stand for minute (so my bad on previous code)

    NB^2: the code "new Date(s)" is definitely deprecated and bad and wrong as per previous discussion. If it matters there's probably a more canonical answer involving essentially the same thing but with Calendars.