可能是因为excel版本的问题的,excel日期的格式为yyyy-mm-dd,用cells[1].getContents().trim()得到的值是yy-mm-dd,比如在excel里面的值是2010-12-15,读到的是10-12-15,让我很头疼了。最后查了很长的时间,终于用下面的方法解决了,代码如下:
判断是否是日期的格式
if (cells[1].getType() == CellType.DATE) {
DateCell dateCell = (DateCell) cells[1];
Date date = dateCell.getDate();
String year = new SimpleDateFormat("yyyy-MM-dd").format(date);
info.setYear(parseTimestamp(year)); //发文日期
}
//说明:parseTimestamp是一个转化时间的方法,因为考虑到日期的格式可能为2010/12/14,代码如下:
//转换时间戳
public Timestamp parseTimestamp(String date) {
String d = date;
if (date.indexOf("/") > 0) {
d = date.replace("/", "-");
}
String temp = d + " 00:00:00";
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time = df.parse(temp);
return new Timestamp(time.getTime());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
当然可能也有人会把日期写成文本的格式,所以可以在判断是否是日期格式的后面,再加一个判断,代码如下:
1 if (cells[1].getType() == CellType.LABEL) {
2 info.setYear(parseTimestamp(cells[1].getContents().trim()));//项目起始日期
3 }