How to convert Java Date to OADate or vice versa?

假如想象 提交于 2019-12-19 11:56:31

问题


I want to convert Java Date to Microsoft OLE Automation - OADate type or want to convert OADate to Java Date. What is the formula of the OADate for Java? Actually I have searched in the stackoverflow and couldnt find the answer, I got the answer and want to share it in this community.

For Example: 43013.7659837963 equals to Thu Oct 05 18:23:01 EET 2017


回答1:


Microsoft's OLE Automation Date Converter for Java

How to convert Java Date to 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);
    }

How to convert OADate to 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();
}


来源:https://stackoverflow.com/questions/43519005/how-to-convert-java-date-to-oadate-or-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!