我有一个CSV文件,其中包含以下数据:
red, 03/11/2014, 11:00, 10
blue, 04/11/2014, 12:00, 15
pink, 03/11/2014, 15:00, 50
blue, 05/11/2014, 14:00, 15
pink, 02/11/2013, 12:00, 10
green, 03/12/2014, 23:00, 1
red, 03/11/2013, 23:11, 11
我正在尝试打印日期和时间,但一直都在失败。
时代码工作正常public static final String DATE_TIME_FORMAT_DATA = "dd/MM/yyyy HH:mm";
更改为
public static final String DATE_FORMAT = "dd/MM/yyyy";
但这只会打印日期。
代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class RangeCalculator {
private File file;
public static final String DATE_TIME_FORMAT_DATA = "dd/MM/yyyy HH:mm";
public class Entry {
String colour;
String date;
String time;
String noise;
public Entry(String colour, String date, String time, String noise) {
super();
this.colour = colour;
this.date = date;
this.time = time;
this.noise = noise;
}
// implement getters and setters here if necessary
@Override
public String toString() {
return "Entry [colour=" + colour + ", date=" + date + ", time="
+ time + ", noise=" + noise + "]";
}
}
public RangeCalculator(String fileName) {
file = new File(fileName);
}
private List<Entry> computeRange(String from, String to)
throws FileNotFoundException, ParseException {
List<Entry> result = new LinkedList<>();
SimpleDateFormat formatter = new SimpleDateFormat(DATE_TIME_FORMAT_DATA);
Date fromDate = formatter.parse(from);
Date toDate = formatter.parse(to);
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[,\n]");
// maybe you want/need to skip the first line of the file
// if (scanner.hasNextLine()) {
// scanner.nextLine();
// }
while (scanner.hasNextLine()) {
String color = scanner.next();
String date = scanner.next().substring(1);
String time = scanner.next().substring(1);
String noise = scanner.next().substring(1);
Date currDate = formatter.parse(date);
if (!currDate.before(fromDate) && !currDate.after(toDate)) {
result.add(new Entry(color, date, time, noise));
}
}
scanner.close();
return result;
}
private void printEntries(List<Entry> entries) {
for (Entry entry : entries) {
System.out.println(entry.toString());
}
}
public static void main(String[] args) {
RangeCalculator app = new RangeCalculator("Data.csv");
List<Entry> calculatedEntries = null;
try {
calculatedEntries = app.computeRange("03/11/2014 11:00", "04/11/2014 12:00");
} catch (FileNotFoundException e) {
System.err.println("ERROR: File not found!");
System.exit(1);
} catch (ParseException e) {
System.err.println("ERROR: Wrong date format!");
System.exit(1);
}
app.printEntries(calculatedEntries);
System.exit(0);
}
}
感谢任何帮助。
答案 0 :(得分:3)
您只是尝试使用包含日期和时间的格式化程序来解析日期。 您需要做的就是替换这一行:
Date currDate = formatter.parse(date);
用这个:
Date currDate = formatter.parse(date + " " + time);
答案 1 :(得分:1)
当您将日期和时间组件作为两个单独的字段时,您需要在使用之前将它们都附加。因此,下面应
日期currDate = formatter.parse(日期+“”+时间);