java - 我如何比较从 csv 文件中读取的日期,以便我只计算那些帖子与那个月?
问题描述
我目前很难过滤出我通过 opencsv 从 2 个 CSV 文件中检索到的日期。我希望按月过滤日期,以便我可以计算每个月的帖子数量并通过 javaFX 折线图显示。例如,y 轴是帖子的数量,x 轴是月份。到目前为止,根据我下面的代码,它只是打印出“它不比较”的列表。到目前为止,我已经设法将日期转换为字符串格式,这样它只会打印出月份、二月、一月、十二月等......
csv 文件中的日期格式为:
csv file 1: Feb 14, 2020, 8:03 pm
csv file 2: 2020-01-20T16:34:57+0800
代码
int febCounter = 0;
int janCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
CSVReader csvReader = new CSVReader(reader);){
String [] nextRecord;
while((nextRecord = csvReader.readNext()) != null) {
String retrievedate = nextRecord[2];
Date date = sdf.parse(retrievedate);
String strDate = sdf.format(date);
if(strDate.equals("Feb")) {
febCounter++;
}
else {
System.out.println("it is not comparing");
}
System.out.println(febCounter);
}
} catch(IOException e) {
System.out.print("File can't be found");
}
预期输出
Feburary: 50
January: 20
December: 10
当前输出
it is not comparing
it is not comparing
it is not comparing
it is not comparing
很快....
更新
所以我能够修复我的错误,我需要对检索到的日期进行两次格式化,一次是格式化日期,以便我只有月份,第二种格式是将日期转换为字符串,例如“strDate.equals ("Feb")" 将起作用。
解决方案
您可以添加文件内容的真实示例吗?您有两个 csv 文件,每个文件都有不同的日期格式。
让我们使用第一个策略,如果您有“2020 年 2 月 14 日,晚上 8:03”,那么 nextRecord 变量将是:
[
0 => "Feb 14",
1 => "2020",
2 => "8:03 pm",
]
而且您必须测试 nextRecord[0].startWith("Feb") 是否不相等。
推荐阅读
- ruby - Ruby - telnet 行为不一致
- java - 通过 Java 代码在另一个 shell 脚本中执行 shell 脚本
- python - 使用 pyspark 不进行聚合的枢轴函数
- vbscript - 如何在经典 ASP 中将字符串转换为字节数组
- java - 在wiremock响应中编码特殊字符
- javascript - 选择在 ajax 自动完成中显示未定义的部分
- package - R管道工和jsonlite包冲突
- c++ - 观察者模式(C++):将模板类从子类转换为模板的基类
- ios - CountdownLabel 检查是否完成
- c# - 如何使用 AmazonS3EncryptionClientV2 客户端加密从 AWS S3 存储桶下载对象?