Program in Java to convert a date to serial number as done in Excel

前端 未结 3 1998
感动是毒
感动是毒 2020-12-22 09:41

I have written a function but it does not give an actual O/P...

public int date(Object O) {
    if (O instanceof Date) {
        Date d1 = (Date) O;
                 


        
相关标签:
3条回答
  • 2020-12-22 10:18

    Try this:

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

    See java.util.Date JavaDoc && Excel Date Function Guide

    0 讨论(0)
  • 2020-12-22 10:23

    The problem in the program is :

    In the program, variable mm(month) is coming as 4 and O/P is coming for 4th month only. (The first month of the year is 0)

    To Solve this, you need to increase the month value.

        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;
    
    0 讨论(0)
  • 2020-12-22 10:26

    The right algorithm is already implemented in Apache POI. Take a look at class org.apache.poi.ss.usermodel.DateUtil.

    Also this description could be useful: http://support.microsoft.com/kb/214094/en-us

    0 讨论(0)
提交回复
热议问题