【问题标题】:Reading and formatting date from a CSV file in Java [duplicate]从Java中的CSV文件读取和格式化日期[重复]
【发布时间】:2021-03-06 18:15:30
【问题描述】:

我对 Java 和一般编程还是很陌生。我有一个项目,其中有一个必须读取的 CSV 文件。在 CSV 的第 3 列中,我有一个日期,我需要在 Java 中将其格式化为 dd/MM/yyyy。然后我需要制作一个对象列表,其中日期是字段之一。 使用我在此处找到的类似问题的答案,我编写了以下代码:

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]));
        }

但是,这并不能满足我的需要,当我尝试打印列表时,日期的格式类似于“EEE,d MMM yyyy HH:mm:ss Z”。 我应该对我的代码进行哪些更改?

【问题讨论】:

  • 没什么,你有一个你想要的 Date 对象。它在控制台中的打印方式在这里并不重要,它只是用于显示 Date 对象的实际值的默认格式。请注意,尽管 SimpleDateFormat 很旧,但您应该改用 DateFormatter。
  • 我建议你不要使用SimpleDateFormatDate。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time APILocalDateDateTimeFormatter。由于旧类在 2014 年被取代,我担心作为一个新的 Java 程序员,你完全遇到过它们。

标签: java date date-format java-time


【解决方案1】:

在打印时,您可以使用相同的 SimpleDateFormat

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

注意:LocalDate 类正在接管 Date 类

【讨论】:

  • 在推荐LocalDate的同时为什么还要使用SimpleDateFormat?
  • 我不确定他使用的是哪个版本的 Java。如果他符合我提供的示例的日期。如果可以,我推荐替代方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
相关资源
最近更新 更多