简体   繁体   English

在CSV数据中将字符串解析为小时

[英]Parse String to Hours in CSV data

I have been trying to parse the String I got from the CSV file and convert the column "start" to hour. 我一直在尝试解析从CSV文件获得的字符串,并将“开始”列转换为小时。 Here is my code: 这是我的代码:

public class BeerSong {


    private static final String csvFileName = "HourList201403.csv";
    public static void main (String[] args) throws IOException, java.text.ParseException {        

        CSVReader csvReader = new CSVReader(new FileReader(csvFileName));
        List<String[]>allLine = csvReader.readAll();

        SimpleDateFormat start = new SimpleDateFormat("HH:mm");
        Calendar calendar = GregorianCalendar.getInstance();
        int startH;
        Date startHour;
        for (String[] line : allLine) {
            startHour=start.parse(line[3]);
            calendar.setTime(startHour);
            startH = calendar.get(Calendar.HOUR);
            System.out.println(line[3]+", "+line[4]);
            System.out.println("Work: "+startH);            
        }
    }
}

When I try to run, it outputs an error: 当我尝试运行时,它输出错误:

Exception in thread "main" java.text.ParseException: Unparseable date: "Start" 线程“主”中的异常java.text.ParseException:无法解析的日期:“开始”

So, what am I doing wrong here and how to fix this ? 那么,我在这里做错什么以及如何解决呢?

The CSV format is like this, it has a lot rows so I put some here: CSV格式是这样的,它有很多行,所以我在这里放了一些:

Person Name, Person ID, Date, Start, End
Scott Scala, 2, 2.3.2014, 6:00, 14:00
Janet Java, 1, 3.3.2014, 9:30, 17:00
Scott Scala, 2, 3.3.2014, 8:15, 16:00
Larry Lolcode, 3, 3.3.2014, 18:00, 19:00

The java.text.ParseException is thrown on attempting to parse the string "Start" as a Date . 尝试将字符串“ Start”解析为Date抛出java.text.ParseException

Clearly that's the header of your spreadsheet, so you should skip the first row (note index 1 here): 显然,这就是电子表格的标题,因此您应该跳过第一行(在此处注意索引1):

 for (int i = 1; i < allLine.size(); i++) {

Note that you'll need the rest of the fields in your column 3 to consistently be of format HH:mm , ie not empty, etc. 请注意,您将需要第3列中的其余字段始终为HH:mm格式,即不为空等。

The trick here is to either use fast-enumeration and skipping the first line, or as I display above, use an int -based iteration starting at index 1 (collections are 0-based, so that'll skip the first item). 这里的技巧是要么使用快速枚举并跳过第一行,要么如我上面显示的,使用从索引1开始的基于int的迭代(集合基于0,因此将跳过第一项)。

You run through all of the parsed lines in your loop. 您遍历循环中所有已分析的行。 The first line is: Person Name, Person ID, Date, Start, End . 第一行是: Person Name, Person ID, Date, Start, End So the 4th item which you want to read out with: startHour=start.parse(line[3]); 因此,您要读取的startHour=start.parse(line[3]);内容是: startHour=start.parse(line[3]); is Start . Start I think you have to skip the first line in your loop with: 我认为您必须跳过循环的第一行:

for(int i = 1; i < allLine.size(); i++){ String[] line = allLine.get(i);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM