电子表格(MS Excel,Google Apps)表示日期为1900年1月1日以来的整天数量(可能是 在Excel的情况下,警告2月29日)。好的,除了leap年,这是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),需要考虑LEAP年。 31536000秒为365天。在4年中,有3个使我从1月1日到1月1日。但是在第四年,我只能从1月1日到12月31日,给我每4年的1天错误!

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

有帮助吗?

解决方案

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

    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);
}

其他提示

在这里对Java的日期API的细节知识很少,但是如果您能找到一种给您Unix时间戳的方法,则应该能够弄清楚它 - unix时间戳是Epoch以来的秒数(1月1日,1970年1月1日,0 :00:00 UTC),因此您需要做的就是找到两个日期的UNIX时间戳,减去,除以86400(一天中的秒数)并切断了分数部分。

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

您可以使用 myGcalEarlier.getTimeInMillis()myGcalLater.getTimeInMillis() 然后通过一天的数量分配毫秒来转换为几天。 24*60*60*1000。而且您的第一个电话是错误的。

set(int year, int month, int date)

一个月为1月0

Gregoriancalendar mygcalearlier = new GregorianCalendar(); Gregoriancalendar mygcallater = new GregorianCalendar(); mygcalearlier.set(1900,日历。1月1日);

long ltime1 = mygcalearlier.getTimeInmillis(); long ltime2 = mygcallater.getTimeinmillis();

长天=(ltime2 -ltime1)/(24*60*60*1000);

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top