从Excel工作表中格式化date
我正在通过Apache POI从我的Java程序的Excel工作表中读取date列,返回stringFri Jan 16 00:00:00 EST 2015
。 我需要格式化这个string到01/16/2016
。
我尝试使用SimpleDateFormat
将Stringparsing为Date
对象,然后返回到我需要的格式化的String
String inputDate = excelData.get(20).toString(); // Returns Fri Jan 16 00:00:00 EST 201 Date date = new SimpleDateFormat("MM/dd/yyyy").parse(inputDate); String outputDate = new SimpleDateFormat("MM/dd/yyyy").format(date);
但是,尝试parsinginputDate
时返回以下inputDate
Unparseable date: "Fri Jan 16 00:00:00 EST 2015"
我的inputDate
不可读的还是我在这里错过了一些东西? 我也想过格式化单元格本身到适当的date格式,而不是思路?
你的问题在这一行:
Date date = new SimpleDateFormat(**"MM/dd/yyyy"**).parse(inputDate);
你所描述的date格式更像是:“DDD MMM DD HH:mm:ss tz yyyy”或类似的东西。
使用https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html查找正确的格式化程序以便读取date。
输出看起来很好,因为您可以将inputstring格式作为正确格式读入date。
你的代码告诉SimpleDateFormat
使用MM/dd/yyyy
格式来分隔date,所以当然它不能工作,因为这不是你得到的string的格式。
https://poi.apache.org/faq.html#faq-N1008D上的POI FAQ提供了一段代码来读取date:
case HSSFCell.CELL_TYPE_NUMERIC: double d = cell.getNumericCellValue(); // test if a date! if (HSSFDateUtil.isCellDateFormatted(cell)) { // format in form of M/D/YY cal.setTime(HSSFDateUtil.getJavaDate(d)); cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2); cellText = cal.get(Calendar.MONTH)+1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText; }
你尝试过吗?
更改
Date date = new SimpleDateFormat("MM/dd/yyyy").parse(inputDate);
至
Date date = new SimpleDateFormat("EEE MMM DD HH:mm:ss zzz yyyy").parse(inputDate);
zzz Time zone EST EEE Day name in week Tuesday MMM Month in year July
参考: SimpleDateFormat文档