---
title: "【转】JXL获取Excel单元格的日期（DateCell.getDate）与实际填写日期相差8小时的解决方法"
author: "foohsinglong"
date: "2010-12-14T16:06:31Z"
tags: []
categories: ["编程语言"]
slug: "jxl-excel-datecell-getdate-8"
draft: false
lastmod: "2010-12-23T11:36:04Z"
id: 841928
url: "https://foohsinglong.iteye.com/blog/841928"
---

用JXL获取的时间总是比Excel单元格实际填写的时间早八小时，例如
单元格中日期为“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″；

这种问题产生的原因 是JXL按照GMT时间来解析Excel单元格的时间，它始终认为被解析的单元格填写的时间 为格林威治时间，然后我们在本地getDate的时候会将格林威治时间转成本地时间，因此会相差8小时。
详见：jxl.read.biff.DateRecord.java类

```java

private static final TimeZone gmtZone = TimeZone.getTimeZone("GMT");
```

1、首先在D盘建立一个xls表(tests.xls)，在A1单元格随便填写一个日期，例如2010-4-11 0:00:00
2、测试类：

```java
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--&gt;"+ 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);
	}
}
```