通过jxl 读取excel 文件中的日期,并计算时间间隔

java读取excel里面的日期会出现相差8小时的问题。

比如excel里面有一个日期是:2012-7-2 17:14:03秒,用Cell cell=readSheet.getCell(colNo, rowNo);调试该cell,发现里面的值竟然是2012-7-3 1:14:13,相差了8小时。

更奇怪的是,用String date=cell.getContents()后,得到的值竟然是2012-7-2 5:14:03分了,将24小时制变成了12小时制了。

原因是:

1、对于Date型的单元格,不应该用cell.getContents(),应该用别的方法,见如下示例。

2、还有一个就是时区问题,要用GMT时区。

具体参见以下示例:

  1. Cell cell = readSheet.getCell(colNo, rowNo);  
  2.                         String cellValue=null;  
  3.                         if (cell.getType() == CellType.DATE)   
  4.                         {   
  5.                             DateCell dc = (DateCell) cell;   
  6.                             Date date = dc.getDate();   
  7.                             TimeZone zone = TimeZone.getTimeZone("GMT");  
  8.                             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  9.                             sdf.setTimeZone(zone);  
  10.                             cellValue = sdf.format(date);                             
  11.                         } else{  
  12.                             cellValue = cell.getContents();  
  13.                         }                         

这种情况下,计算时间间隔,可以首先计算相对于同一个时间始点,不同时间点距离该时间始点的分钟数,并进而求得这个时间间隔,如下

List month=new ArrayList();
month.add(31);//1月
month.add(60);
month.add(91);
month.add(121);
month.add(152);
month.add(182);
month.add(213);
month.add(244);
month.add(274);
month.add(305);
month.add(335);
month.add(366);//累积天数

time_=(int)month.get(Integer.parseInt(cellValue.substring(5, 7))-2)*24*60+(Integer.parseInt(cellValue.substring(8, 10))-1)*24*60+Integer.parseInt(cellValue.substring(11, 13))*60+Integer.parseInt(cellValue.substring(14, 16));

上述代码,可以计算某时间点距离16年1月1日凌晨0时的分钟数,同理可以计算另外一个时间距离16年1月1日凌晨0时的分钟数,两个分钟数相减,得到两个时间点的时间间隔。

以上为jxl处理时候的一些特殊操作,一般情况下,java中计算时间采用Date类,如下

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date time1 = df.parse(temp1);//temp1为包含时间的字符串
timeGap=(time1.getTime()-time.getTime())/1000;  //timeGap单位为毫秒

long day=timeGap/(24*60*60);
long hour=(timeGap/(60*60)-day*24);
long min=((timeGap/(60))-day*24*60-hour*60);
long s=(timeGap-day*24*60*60-hour*60*60-min*60);
System.out.println("格式化的时间"+day+"天"+hour+"小时"+min+"分"+s+"秒");

http://blog.csdn.net/jeamking/article/details/7288353

http://wandejun1012.iteye.com/blog/1585322

原文地址:https://www.cnblogs.com/bnuvincent/p/5978587.html