Java Epoch Date for Google SpreadSheet

有些话、适合烂在心里 提交于 2020-01-25 19:58:09

问题


I tried to add date on Google spreadsheet. To add date we have convert date in epoch.

For Spreadsheet epoch

Google Sheets uses a form of epoch date that is commonly used in spreadsheets. The whole number portion of the value (left of the decimal) counts the days since December 30th 1899. The fractional portion (right of the decimal) counts the time as a fraction of one day. For example, January 1st 1900 at noon would be 2.5, 2 because it's two days after December 30th, 1899, and .5 because noon is half a day. February 1st 1900 at 3pm would be 33.625.

We uses Joda time API for calculation.(Our JDK version 1.7).

For Whole number we uses below code.

public static double getEpochDate(Date inputDate)
{

    MutableDateTime epoch = new MutableDateTime();
    epoch.setTime(0, 0, 0, 0);
    epoch.setDate(1899,12,30); //Set to Epoch time
    System.out.println(epoch);
    DateTime now = new DateTime(inputDate);
    Days days = Days.daysBetween(epoch, now);


    return Double.valueOf(days.getDays());
}

We are facing issue to find faction part of epoch number


回答1:


One option would be to take the "milliseconds since the Unix epoch" value (e.g. with Date.getTime()), offset that to get "milliseconds since the Sheets epoch" and then perform a floating point division by 24 hours. Something like this:

// Precomputed difference between the Unix epoch and the Sheets epoch.
private static final long SHEETS_EPOCH_DIFFERENCE = -2209161600000L;

public static double getEpochDate(Date date)
{
    long millisSinceUnixEpoch = date.getTime();
    long millisSinceSheetsEpoch = millisSinceUnixEpoch - SHEETS_EPOCH_DIFFERENCE;
    return millisSinceSheetsEpoch / (double) TimeUnit.DAYS.toMillis(1);
}

No need for Joda Time to get involved in this case. (When you do want to use Joda Time, I'd strongly advise avoiding the Mutable* types. And only use DateTime when there's genuinely a time zone involved...)



来源:https://stackoverflow.com/questions/38015854/java-epoch-date-for-google-spreadsheet

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