[英]Decimal DateTime formatter in Java or Joda
I'm writing a file that requires dates to be in decimal format:我正在编写一个要求日期为十进制格式的文件:
2007-04-24T13:18:09
becomes39196.554270833331000
2007-04-24T13:18:09
变成39196.554270833331000
Does anyone have a time formatter that will do this (Decimal time is what VB/Office, etc. use)?有没有人有时间格式化程序可以做到这一点(十进制时间是 VB/Office 等使用的)?
Basic code goes like follows:基本代码如下:
final DateTime date = new DateTime(2007, 04, 24, 13, 18, 9, 0, DateTimeZone.UTC);
double decimalTime = (double) date.plusYears(70).plusDays(1).getMillis() / (Days.ONE.toStandardDuration().getMillis())); //=39196.554270833331000.
For the example above.对于上面的例子。
(I started on a DateTimePrinter that would do this, but it's too hard for now (I don't have the joda source linked, so I can't get ideas easily)). (我开始使用可以执行此操作的 DateTimePrinter,但现在太难了(我没有链接 joda 源,因此我无法轻松获得想法))。
Note: Decimal time is the number of days since 1900 - the .注意:十进制时间是自 1900 年以来的天数 - . represents partial days.
代表部分天数。 2.6666666 would be 4pm on January 2, 1900
2.6666666 将是 1900 年 1 月 2 日下午 4 点
You can create a formatter that outputs the decimal fraction of the day.您可以创建一个格式化程序来输出当天的小数部分。 You need to use
DateTimeFormatterBuilder
to build up the pattern manually.您需要使用
DateTimeFormatterBuilder
手动构建模式。 The fraction is added using appendFractionOfDay() .使用appendFractionOfDay()添加分数。
You can do this using the calendar class:您可以使用日历类来执行此操作:
final long MILLIS_IN_DAY = 1000L * 60L * 60L * 24L;
final Calendar startOfTime = Calendar.getInstance();
startOfTime.setTimeZone(TimeZone.getTimeZone("UTC"));
startOfTime.clear();
startOfTime.set(1900, 0, 1, 0, 0, 0);
final Calendar myDate = Calendar.getInstance();
myDate.setTimeZone(TimeZone.getTimeZone("UTC"));
myDate.clear();
myDate.set(2007, 3, 24, 13, 18, 9); // 2007-04-24T13:18:09
final long diff = myDate.getTimeInMillis() - startOfTime.getTimeInMillis() + (2 * MILLIS_IN_DAY);
final double decimalTime = (double) diff / (double) MILLS_IN_DAY;
System.out.println(decimalTime); // 39196.55427083333
Something to note: This code will only work after 28th February 1900. Excel incorrectly counts 1900 as a leap year, which it of course is not .需要注意的是:此代码仅在 1900 年 2 月 28 日之后有效。Excel错误地将 1900 计算为闰年,当然不是。 To circumvent the bug the calculation inserts an extra day (
2 * MILLIS_IN_DAY
), but this of course corrupts any date calculations before the imaginary leap year took place.为了规避该错误,计算插入了额外的一天(
2 * MILLIS_IN_DAY
),但这当然会在假想的闰年发生之前破坏任何日期计算。
getTime()方法有什么问题?
Unfortunately your question is not very clear, but I have a hunch that with decimal time you mean a Julian date .不幸的是,你的问题不是很清楚,但我有一种预感,十进制时间你的意思是儒略日期。 There is a post about converting date to julian date in Java.
有一篇关于在 Java中将日期转换为儒略日期的帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.