0

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?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Peter
  • 29
  • 1
  • 6
  • 2
    Nothing really, you have a Date object which is what you want. The way it is printed in the console is not important here, it is just a default format used to display the actual value of your Date object. Beware though that SimpleDateFormat is old and that you should use DateFormatter instead. – Joakim Danielson Mar 06 '21 at 18:22
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Since the old classes were supplanted in 2014, it worries me that as a new Java programmer you have encountered them at all. – Ole V.V. Mar 06 '21 at 20:05

1 Answers1

1

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

Dina
  • 41
  • 3
  • 4
    Why do you use SimpleDateFormat when you at the same time recommend LocalDate? – Joakim Danielson Mar 06 '21 at 18:24
  • I was not sure which version of Java he was using. If he is complies with Date I provided example. If he can, I recommended alternative. – Dina Mar 07 '21 at 01:12