`

JXL获取Excel单元格的日期(DateCell.getDate)与实际填写日期相差8小时的解决方法

    博客分类:
  • Java
阅读更多
这种问题产生的原因是JXL按照GMT时间来解析Excel单元格的时间,它始终认为被解析的单元格填写的时间为格林威治时间,然后我们在本地getDate的时候会将格林威治时间转成本地时间,因此会相差8小时。
详见:jxl.read.biff.DateRecord.java类
private static final TimeZone gmtZone = TimeZone.getTimeZone("GMT");


因gmtZone为final的,我们不能通过setTimeZone这种方法来改变时区,只能在JXL获取时间以后重新转成本地时间。
测试开始:
1、首先在D盘建立一个xls表(tests.xls),在A1单元格随便填写一个日期,例如2010-4-11 0:00:00
2、测试类:
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class JXLTest {
    public static void main(String[] args) throws BiffException, IOException, ParseException {
       Workbook workBook = Workbook.getWorkbook(new File("D:\\test.xls"));
       Sheet sheet = workBook.getSheet(0);
       DateCell cell = (DateCell)sheet.getCell(0, 0);
       System.out.println("Get date by JXL:"+cell.getDate());
       System.out.println("After converting,we can get the time we had writed-->"+convertDate4JXL(cell.getDate()));
    }
   
    /**
     * JXL中通过DateCell.getDate()获取单元格中的时间为(实际填写日期+8小时),原因是JXL是按照GMT时区来解析XML。本方法用于获取单元格中实际填写的日期!
     * 例如单元格中日期为“2009-9-10”,getDate得到的日期便是“Thu Sep 10 08:00:00 CST 2009”;单元格中日期为“2009-9-10 16:00:00”,getDate得到的日期便是“Fri Sep 11 00:00:00 CST 2009”
     * @author XHY
     * @param jxlDate 通过DateCell.getDate()获取的时间
     * @return
    * @throws ParseException
     */
    public static java.util.Date convertDate4JXL(java.util.Date jxlDate) throws ParseException{
    if(jxlDate==null)
        return null;
       TimeZone gmt = TimeZone.getTimeZone("GMT");
       DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
       dateFormat.setTimeZone(gmt);
       String str = dateFormat.format(jxlDate);
      
       TimeZone local = TimeZone.getDefault();
       dateFormat.setTimeZone(local);
       return dateFormat.parse(str);
    }
}


输出结果是:

Get date by JXL:Sun Apr 11 08:00:00 CST 2010
After converting,we can get the time we had writed-->Sun Apr 11 00:00:00 CST 2010
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics