使用java在xls中将String转换为Date格式

时间:2013-10-24 08:19:35

标签: java apache-poi

我想在下面的代码中将String (returns string :odb.getCloseDate())转换为Date。但是我没有得到这个格式"23/10/2013"的输出。请纠正我在哪里犯错误。 在数据库表中的值是这个格式:2013-06-30并且我通过bean检索这个数据,即odb.getCloseDate()。现在我需要在这个格式中显示这个日期,即23/10/2013。

        HSSFCell row1 = row.createCell((short) j);
        //row1.setCellType(row1.CELL_TYPE_NUMERIC);

        try
        {
            //row1.setCellValue( Date.parse(odb.getCloseDate()));
            DateFormat formatter;
            Date date;
            formatter = new SimpleDateFormat("dd/MM/yyyy");
            row1.setCellValue(date = formatter.parse(odb.getCloseDate()));

        }
        catch (Exception e)
        {
            row1.setCellValue(odb.getCloseDate());
        }

2 个答案:

答案 0 :(得分:3)

Date and Time Patterns

mm表示MinutesMM表示Month

formatter  = new SimpleDateFormat("dd/MM/yyyy");

而不是

formatter  = new SimpleDateFormat("dd/mm/yyyy");

试试这个,

        String dateValue = "2013-06-30"; //consider as your date.
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// First apply the patern to the incoming date value. Because it doesnt know the actual incming format
        Date actualDate = simpleDateFormat.parse(dateValue);
        simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        System.out.println(simpleDateFormat.format(actualDate));

答案 1 :(得分:1)

在您的日期格式mm应为MM

原因

m   Minute in hour

其中

M   Month in year

您需要Month in year而不是Minute in hour

然后你的格式化程序变为

formatter  = new SimpleDateFormat("dd/MM/yyyy");

Have a look on different formats here.