java - 对于给定的 `Date`,我能否仅使用 `java.*` API 得出自 1900 年 1 月 1 日以来的天数?

标签 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 可以获取以日历天数表示的准确差异?

注意事项

我确实想要日历日,而不是 days-of-86400-seconds。除了时区和夏令时(感谢@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 中的“受信任”库。到目前为止,我的结论是“不”。

最佳答案

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

    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 - 对于给定的 `Date`,我能否仅使用 `java.*` API 得出自 1900 年 1 月 1 日以来的天数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4699271/

相关文章:

python - 日期时间的国际化

java - 将具有给定偏移量的日期时间转换为 UTC Java

java - 当我最小化框架时面板组件消失

java - HSQLDB:使用 java 插入/获取日期

java - JUL 配置类应该如何(以及为什么)初始化?

ios - 如何在iOS上的月 View 日历上绘制跨多日的多日事件矩形?

java - Android 日历序列化与 Java 6 不兼容

java - 在GMT时区中保存和检索Date并将其转换为String

JavaFX - 加载自定义控件的样式表

java - 使用java流从集合集合中删除一些值