有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java格式化Excel工作表中的日期

我正在通过ApachePOI从Java程序中的Excel工作表中读取一个日期列,它返回字符串Fri Jan 16 00:00:00 EST 2015。我需要将这个字符串格式化为01/16/2016

我尝试使用SimpleDateFormat将字符串解析为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);

但是,当试图解析inputDate时,将返回以下内容

Unparseable date: "Fri Jan 16 00:00:00 EST 2015"

我的inputDate是不可读的,还是我遗漏了什么?我还想过将单元格本身格式化为正确的日期格式——想法


共 (2) 个答案

  1. # 1 楼答案

    改变

    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 doc

  2. # 2 楼答案

    您的代码告诉SimpleDateFormat使用MM/dd/yyyy格式来解析日期,因此它当然不能工作,因为这不是您得到的字符串的格式

    位于https://poi.apache.org/faq.html#faq-N1008D的POI FAQ给出了读取日期的代码片段:

    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;
         }
    

    你试过了吗