如何将Java Date转换为OADate,反之亦然?

时间:2017-04-20 12:03:38

标签: java ole-automation java-date

我想将Java Date转换为Microsoft OLE Automation - OADate类型或想要将OADa​​te转换为Java Date。 OADate for Java的公式是什么? 实际上我已经在stackoverflow中搜索并找不到答案,我得到了答案并希望在这个社区中分享它。

例如: 43013.7659837963 等于 Thu Oct 05 18:23:01 EET 2017

1 个答案:

答案 0 :(得分:1)

Microsoft的OLE自动化日期转换器for Java

如何将Java Date转换为OADate:

    /**
    * Convert Date to Microsoft OLE Automation - OADate type
    * @param date
    * @return
    * @throws ParseException
    */
    public static String convertToOADate(Date date) throws ParseException {
    double oaDate;
    SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
    Date baseDate = myFormat.parse("30 12 1899");
    Long days = TimeUnit.DAYS.convert(date.getTime() - baseDate.getTime(), TimeUnit.MILLISECONDS);

    oaDate = (double) days + ((double) date.getHours() / 24) + ((double) date.getMinutes() / (60 * 24)) + ((double)                     date.getSeconds() / (60 * 24 * 60));
    return String.valueOf(oaDate);
    }

如何将OADa​​te转换为Java Date:

/**
 * Convert Microsoft un OLE Automation - OADate to Java Date.
 * @param date
 * @return
 * @throws ParseException
 */
public static Date convertFromOADate(double d) throws ParseException {
    double  mantissa = d - (long) d;
    double hour = mantissa*24;
    double min =(hour - (long)hour) * 60;
    double sec=(min- (long)min) * 60;


    SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
    Date baseDate = myFormat.parse("30 12 1899");
    Calendar c = Calendar.getInstance();
    c.setTime(baseDate);
    c.add(Calendar.DATE,(int)d);
    c.add(Calendar.HOUR,(int)hour);
    c.add(Calendar.MINUTE,(int)min);
    c.add(Calendar.SECOND,(int)sec);

    return c.getTime();
}