如何拆分同一列上的日期和时间并将它们存储在 ArrayList 中?

How to I split date and time that are on the same column and store them in an ArrayList?

我正在使用 'JFreeChart' 创建数据可视化程序,但在使用 BufferedReader 从 CSV 文件读取数据时遇到问题。在 CSV 文件中,我将日期和时间存储在同一列中。我知道我必须使用 " " 函数来分隔它们,但我不知道该怎么做。

我试过到处寻找,但我无法确定。我需要被推到正确的轨道上。

//This is part of my Data Class

private int millis;
    private int stamp;
    private int light; 
    private double temp;
    private double vcc;
    private Time theTime;
    private Date theDate;


//This is part of another class

public class CSVreader {

    private List<Data> dataList = new ArrayList<Data>();
    private String path;

    public List<Data> getDataList() {
        return dataList;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }

    public void readCSV() throws IOException{ 

        BufferedReader in = new BufferedReader (new FileReader(path));

        String line = in.readLine();

        while(line != null) {

            Data d = new Data();

            String[] splits = line.split(",");

            int millis = Integer.parseInt(splits[0]);
            int stamp = Integer.parseInt(splits[1]);
            int light = Integer.parseInt(splits[2]);
            double temp = Double.parseDouble(splits[3]);
            double vcc = Double.parseDouble(splits[4]);

            d.setMillis(millis);
            d.setStamp(stamp);
            d.setLight(light);
            d.setTemp(temp);
            d.setVcc(vcc);

            dataList.add(d);

        }

        }

}

最终结果应该是所有数据都在一个数组列表中,我可以调出这些结果,然后我可以使用 JFreeChart 从列表中创建一个图表。

根据您的评论,将 splits 数组中的第 3 个元素拆分为 space " " 分隔符

String dateTime[] = splits[2].split(" ");
String date = dateTime[0];
String time = dateTime[1];

但我可以看到 dateTime 的数据类型不同

private Time theTime;
private Date theDate;

如果 Datejava.util.Date 您可以使用 SimpleDateFormat 将字符串转换为 Date

DateFormat formatter = new SimpleDateFormat("yyyy/dd/mm");
Date date = formatter.parse(testDate);

根据您对“2010/5/4 21:57:35”的评论 date/time, 更简单的方法可以使用 Joda Time Library

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/M/d HH:mm:ss");
DateTime dt = formatter.parseDateTime("2010/5/4 21:57:35");

然后可以从Datetime获取日期和时间值:

String time = dt.toString("HH:mm:ss");
String date = dt.toString("yyyy/M/d");

但是我看到数据类型不是字符串,如果你想把它解析成日期数据类型可以这样做:

Date date = dt.toDate();