本文介绍了为什么java.util.Date代表年份为“1900年”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.util.Date 中:

 * In all methods of class <code>Date</code> that accept or return
 * year, month, date, hours, minutes, and seconds values, the
 * following representations are used:
 * <ul>
 * <li>A year <i>y</i> is represented by the integer
 *     <i>y</i><code>-1900</code>.

当然,在Java 1.1中, getYear()方法等已被弃用,支持 java.util.Calendar ,它们仍然有一个奇怪的弃用笔记:

Of course, in Java 1.1, the getYear() method and the like were deprecated in favor of java.util.Calendar, which still has this weird deprecation note:

 int    getYear()
    Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.

 setYear(int year)
      Deprecated. As of JDK version 1.1, replaced by Calendar.set(Calendar.YEAR, year + 1900).

当然,月份是 0 但是我们都知道(虽然你会认为他们从 Calendar 中删除​​了这个问题 - 他们没有):

And of course, Month is 0-based but we all know that (although you'd think they had removed that problem from Calendar - they didn't):

 * <li>A month is represented by an integer from 0 to 11; 0 is January,
 *     1 is February, and so forth; thus 11 is December.

我检查了以下问题:

我的问题是:


  • 原始创作者 java.util.Date 希望从存储年的数据中减去1900吗?特别是如果它基本上存储一段时间。

  • What possibly could have the original creators of java.util.Date hoped to gain from storing the data of "year" by subtracting 1900 from it? Especially if it's basically stored as a long.

因此:

private transient long fastTime;

@Deprecated
public int getYear() {
    return normalize().getYear() - 1900;
}

@Deprecated
public void setYear(int year) {
    getCalendarDate().setNormalizedYear(year + 1900);
}

private final BaseCalendar.Date getCalendarDate() {
    if (cdate == null) {
        BaseCalendar cal = getCalendarSystem(fastTime);
    ....




  • 为什么 1900

    • Why 1900?
    • 推荐答案

      基本上原来的java.util.Date设计师复制了很多C.你看到的结果是 - 参见。所以你应该问为什么这个设计是为了使用1900年。我怀疑基本的答案是因为我们在设计 tm 时我们不太熟悉API设计。我认为,因为有很多不同的用例,我们仍然在API设计方面不是很好。

      Basically the original java.util.Date designers copied a lot from C. What you're seeing is the result of that - see the tm struct. So you should probably ask why that was designed to use the year 1900. I suspect the fundamental answer is "because we weren't very good at API design back when tm was designed." I'd contend that we're still not very good at API design when it comes to dates and times, because there are so many different use cases.

      这只是API,而不是 java.util.Date 中的存储格式。不要烦恼,请记住你。

      This is just the API though, not the storage format inside java.util.Date. No less annoying, mind you.

      这篇关于为什么java.util.Date代表年份为“1900年”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 09:50