【发布时间】:2014-05-21 08:16:46
【问题描述】:
我正在接收某人用 excel 编写的 csv 文件,我需要将这些文件解析到我的数据库中。
但是,当我尝试将日期解析为时间戳时,它告诉我格式不正确,并且需要 YYYY-MM-DD hh:mm:ss
对此有两种可能的解决方案,我不确定哪一种实际上可行。
1. 在导出 csv 之前让 excel 将日期转换为 YYYY-MM-DD hh:mm:ss
2. 以某种方式在Java中转换Excel日期格式。
我尝试在 Excel 中更改格式,但我没有看到任何导致 YYYY-MM-DD hh:mm:ss 的格式选项,我得到的最接近的是 YY-MMM-DD 或 MM/DD/YY
1 或 2 哪个更好,我该怎么做?
编辑相关Javacode sn-p:
public static List<AffiliateEntry> convert(ArrayList<String[]> collection) {
List<AffiliateEntry> entryList = new ArrayList<AffiliateEntry>();
HashMap<String, Integer> columnIndex = new HashMap();
for (int col_index = 0; col_index < collection.get(0).length; col_index++) {
columnIndex.put(collection.get(0)[col_index].trim(), col_index);
}
for (int i = 1; i < collection.size(); i++) {
String[] row = collection.get(i);
AffiliateEntry convertedEntry = new AffiliateEntry();
int dateIndx = columnIndex.get("Date") != null ? columnIndex.get("Date") : 0;
Timestamp date = (row[dateIndx] != null && !row[dateIndx].isEmpty()) ? Timestamp.valueOf(row[dateIndx]) :
new Timestamp(System.currentTimeMillis());
convertedEntry.setReport_date(date);
....//more things to convert
}
}
【问题讨论】:
-
您可以在 excel 中制作自定义格式。根据this link,只需点击自定义类别并添加yyy-mm-dd hh:mm:ss。将此格式应用于所有需要的单元格
-
请向我们展示您的代码和 csv 行。
-
@Ploutox 请将其作为答案发布,这是最好的解决方案。谢谢