java excel 日期,用Java程序将日期转换为序列号,就像在Excel中一样

本文探讨了一个Java函数在处理日期时与Excel输出不一致的问题,着重于如何修正`date()`函数以匹配Apache POI中的DateUtil算法。作者分享了遇到的2月29日历史问题,并给出了正确的解决方案。
摘要由CSDN通过智能技术生成

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;

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;

}

Main class

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

}

Output date-----39556

In Excel DATE(2008,5,18) = 39586.00

My program O/P doesn't actually match with Excel O/P.

解决方案

The right algorithm is already implemented in Apache POI.

Take a look at class org.apache.poi.ss.usermodel.DateUtil.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值