2

电子表格(MS Excel、Google Apps)将日期表示为自 1900 年 1 月 1 日以来的整天数(在 Excel 的情况下可能需要注意 2 月 29 日的奇怪情况)。好的,所以除了闰年之外是 365 天。但这已经是太多的算术了。

大概,java.util.[Gregorian]Calendar知道所有这些东西。问题是,我不知道如何访问它的知识。

在投机世界中,人们可能会:

myGcalEarlier.set(1900, Calendar.JANUARY, 1);
myGcalLater.set(new Date());

long days1 = myGcalEarlier.mysteryMethod();
long days2 = myGcalLater.mysteryMethod();

long days = days2 - days1;

可悲的是,Calendar.get(Calendar.DAYS_IN_YEAR)不满足“mysteryMethod”——它需要一个Calendar.DAYS_EVER字段来做我想做的事。

是否有用于获得以日历日表示的准确差异的 API ?

笔记

我真的想要日历天,而不是 86400 秒的天数。除了时区和夏令时问题(感谢@Dipmedeep),还需要考虑闰年。在这些术语中,31536000 秒是 365 天。4 年中有 3 年,这让我从 1 月 1 日到 1 月 1 日。但是在第 4 年,它只让我从 1 月 1 日到 12 月 31 日,每 4 年给我一个 1 天的错误!

已经有了获取日历天数的解决方案。迁移到 Java 是一段微不足道的代码,它得到了想要的答案(尽管我不理解它,因此不信任它)。这个问题专门询问(现在在编辑后更是如此)我是否可以完全避免进行这些计算并将其推迟到 JDK 中的“受信任”库。到目前为止,我的结论是“不”。

4

4 回答 4

1

这是实现目标的一种非常愚蠢且低效的方法,但它可以用于验证其他技术

    public static void main(String[] args) {
      Calendar now = Calendar.getInstance();
      //now.setTime(new Date()); // set the date you want to calculate the days for
      Calendar tmp = Calendar.getInstance();
      tmp.set(0,0,0); // init a temporary calendar.
      int days=0;
      // iterate from 1900 and check how many days are in the year, sum the days 
      for (int i=1900; i < now.get(Calendar.YEAR);i++) {
          tmp.set(Calendar.YEAR, i);
          int daysForThatYear = tmp.getActualMaximum(Calendar.DAY_OF_YEAR);
          days+=daysForThatYear;
          System.out.printf("year:%4d days in the year:%3d, total days:%6d\n",i,daysForThatYear,days);
      }
      // check the number of days for the current year, and add to the total of days
      int daysThisYear = now.get(Calendar.DAY_OF_YEAR);
      days+=daysThisYear;
      System.out.printf("year:%4d days in the year:%3d, total days:%6d\n",now.get(Calendar.YEAR),daysThisYear,days);
}
于 2011-01-15T17:25:35.857 回答
-1

GregorianCalendar myGcalEarlier = new GregorianCalendar(); GregorianCalendar myGcalLater = 新的 GregorianCalendar(); myGcalEarlier.set(1900, Calendar.JANUARY, 1);

长 lTime1 = myGcalEarlier.getTimeInMillis(); 长 lTime2 = myGcalLater.getTimeInMillis();

长天 = (lTime2 - lTime1)/(24*60*60*1000);

于 2011-01-26T14:52:55.107 回答
-1

这里对 java 的日期 API 的细节知之甚少,但如果你能找到一种给你 Unix 时间戳的方法,你应该能够弄清楚 - Unix 时间戳是自纪元以来的秒数(1970 年 1 月 1 日,0 :00:00 UTC),所以您需要做的就是找到两个日期的 Unix 时间戳,减去,除以 86400(一天中的秒数)并截去小数部分。

对于时间点的任何其他线性表示也可以这样做 - 您需要知道的只是如何转换为该线性表示,以及一天中有多少个单位。

于 2011-01-15T11:32:28.650 回答
-1

您可以使用myGcalEarlier.getTimeInMillis()myGcalLater.getTimeInMillis()然后通过以毫秒为单位除以天数来转换为天数。24*60*60*1000。你的第一个电话是错误的。

set(int year, int month, int date)

月份是从 0 开始的 0 表示一月

于 2011-01-15T11:32:31.083 回答