使用 Java 从 CSV 文件中读取时间戳

Reading timestamp from CSV file Using Java

我有一个包含大量数据的 CSV 文件。其中一列包含格式中的日期和时间,例如 Day of week Month Day Time Timezone year 或 "Mon Feb 23 05:30:55 +0000 2015"。

2 月 23 日星期一05:30:56+0000 2015

2 月 23 日星期一05:30:56+0000 2015

2 月 23 日星期一05:30:56+0000 2015

2 月 23 日星期一05:30:56+0000 2015

2 月 23 日星期一05:30:56+0000 2015

2 月 23 日星期一05:30:55+0000 2015

2 月 23 日星期一05:30:55+0000 2015

这些是我拥有的日期和时间数据的一些示例。但是,时间从 01:00:00 到上面列出的时间。

我正在尝试读取该时间列,并在另一列中查找与时间相关的另一数据的计数。

因此,例如,另一列包含数字等数据。

我想找到某个数字显示最多的小时和分钟。

关于时间戳,老实说我不知道​​从哪里开始。如果我现在拥有字符串格式的时间戳,我该如何增加时间戳?不过我只需要小时和分钟。如何从字符串中取出该部分并递增它?

起点:

String string = "Mon Feb 23 05:30:55 +0000 2015";

DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Mon Feb 23 05:30:55 GMT 2015

int hours = date.getHours();
date.setHours(hours + 1);
System.out.println(date); // Mon Feb 23 06:30:55 GMT 2015

UPD: 使用 Calendar 的更好解决方案 class:

String string = "Mon Feb 23 05:30:55 +0000 2015";

DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
Calendar date = Calendar.getInstance();
date.setTime(format.parse(string));
System.out.println(format.format(date.getTime())); // Mon Feb 23 05:30:55 GMT 2015          

int hours = date.get(Calendar.HOUR_OF_DAY); // 5
int minutes = date.get(Calendar.MINUTE); // 30

date.add(Calendar.HOUR_OF_DAY, 1); // add a hour
date.add(Calendar.MINUTE , 1); // add a minute
System.out.println(format.format(date.getTime())); // Mon Feb 23 06:31:55 GMT 2015

您可以使用 uniVocity-parsers 轻松做到这一点:

  CsvParserSettings settings = new CsvParserSettings();
  //processes only these two fields, all others are ignored
  parserSettings.selectFields("your_calendar_field", "your_other_field");

  ObjectRowProcessor rowProcessor = new ObjectListRowProcessor();
  //converts the content of "your_calendar_field" to a java.util.Calendar.
  rowProcessor.convertFields(Conversions.toCalendar("EEE MMM dd HH:mm:ss Z yyyy")).set("your_calendar_field");

  //Creates a parser with the given settings
  CsvParser parser = new CsvParser(settings);
  parser.parse(new FileReader("your_input_file"));

  //returns all rows, ordered as defined in the field selection above,
  //with date Strings properly converted to Calendar.
  List<Object[]> parsedRows = rowProcessor.getRows();

披露:我是这个图书馆的作者。它是开源且免费的(Apache V2.0 许可证)。