使用Java编程将日期转换为序列号,如在Excel中完成

时间:2013-04-12 07:07:07

标签: java excel date

我写了一个函数,但它没有提供实际的O / P ......

public int date(Object O) {
    if (O instanceof Date) {
        Date d1 = (Date) O;
        Calendar cal = Calendar.getInstance();
        cal.setTime(d1);
        int dd, mm, yy;
        dd = cal.get(Calendar.DAY_OF_MONTH);
        mm = cal.get(Calendar.MONTH);
        yy = cal.get(Calendar.YEAR);

        if (dd == 29 && mm == 02 && yy == 1900)
            return 60;

        long nSerialDate = ((1461 * (yy + 4800 + ((mm - 14) / 12))) / 4)
                + ((367 * (mm - 2 - 12 * ((mm - 14) / 12))) / 12)
                - ((3 * (((yy + 4900 + ((mm - 14) / 12)) / 100))) / 4) + dd
                - 2415019 - 32075;

        if (nSerialDate < 60) {
            // Because of the 29-02-1900 bug, any serial date
            // under 60 is one off... Compensate.
            nSerialDate--;
        }

        return (int) nSerialDate;
    }
    return -1;
}

主要班级

p s v main(String args[]){
CommonFunctionsImpl cmp= new CommonFunctionsImpl();
    Date date1 = null;
      try {
        date1 = new SimpleDateFormat("MM/dd/yy").parse("05/18/2008");

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    System.out.println("date-----"+cmp.date(date1));
}

输出 date-----39556

在Excel中 DATE(2008,5,18) = 39586.00

我的程序O / P实际上与Excel O / P不匹配。

3 个答案:

答案 0 :(得分:3)

正确的算法已经在Apache POI中实现。 看看课程org.apache.poi.ss.usermodel.DateUtil

此说明也很有用:http://support.microsoft.com/kb/214094/en-us

答案 1 :(得分:1)

该计划的问题是:

在该计划中,变量mm(month)将为4,而O / P仅在第4个月出现。 (一年中的第一个月是0)

要解决此问题,您需要增加月份值。

    dd = cal.get(Calendar.DAY_OF_MONTH);
    mm = cal.get(Calendar.MONTH);
    yy = cal.get(Calendar.YEAR);

    //Solution for the issue
    mm++;

    if (dd == 29 && mm == 02 && yy == 1900)
        return 60;

    long nSerialDate = ((1461 * (yy + 4800 + ((mm - 14) / 12))) / 4)
            + ((367 * (mm - 2 - 12 * ((mm - 14) / 12))) / 12)
            - ((3 * (((yy + 4900 + ((mm - 14) / 12)) / 100))) / 4) + dd
            - 2415019 - 32075;

答案 2 :(得分:-2)

试试这个:

Date begin = new Date(0, 0, 1); // 1900 based date
Date date = new Date(108, 4, 18); // your date

// There is 2 days offset from the calculated date and what you 
// expect so I added it on the result
System.out.println(2+(date.getTime()-begin.getTime())/(1000*60*60*24));

参见java.util.Date JavaDoc&amp;&amp; Excel Date功能指南