Search code examples
javadatedate-formatjava-time

Reading and formatting date from a CSV file in Java


I am still quite new to Java and programming in general. I have a project where I have a CSV file, which has to be read. In the 3rd column of the CSV I have a date, which I need to format as dd/MM/yyyy in Java. I then need to make a list of objects, where the date is one of the fields. Using answers to similar questions I found here, I wrote this code:

while ((line = br.readLine()) != null) {
            String[] str = line.split(splitBy);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date dt = sdf.parse(str[2]);
            tripLis.add(new Trip(Integer.parseInt(str[0]), str[1], dt,
                    Integer.parseInt(str[3]), Double.parseDouble(str[4]), str[5]));
        }

However, this doesn't do what I need and when I try to print the list the dates is formatted like "EEE, d MMM yyyy HH:mm:ss Z". What should I change in my code?


Solution

  • While printing you can use the same SimpleDateFormat

    Date currentDate = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(simpleDateFormat.format(currentDate));
    

    Note: LocalDate class is taking over Date class