问题
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