我可以使用`java。*`API从给定的`Date`导出1900年1月1日以来的天数吗?

时间:2011-01-15 11:20:55

标签: java calendar datetimeoffset

电子表格(MS Excel,Google Apps)将日期表示为自1900年1月1日以来的整天数(可能是caveat a Feb 29 odditiy in Excel's case)。好的,所以它是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天的错误!

already have a solution for getting the number of calendar days。迁移到Java是一个微不足道的代码,它得到了理想的答案(虽然我不理解它,因此不信任它)。如果我可以完全避免进行这些计算并将其推迟到JDK中的“可信”库,那么这个问题就是特别要求(现在甚至更多编辑后)。到目前为止,我已经结束了'不'。

4 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:-1)

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

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

答案 2 :(得分:-1)

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

set(int year, int month, int date)

月份是0月0日为1月

答案 3 :(得分:-1)

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

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

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

相关问题