ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

为什么java.util.Date将Year表示为“year-1900”?

2019-07-14 16:03:57  阅读:650  来源: 互联网

标签:java date offset java-util-date


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,它仍然有这个奇怪的弃用说明:

 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).

当然,Month是基于0但我们都知道(尽管你认为他们已经从日历中删除了这个问题 – 他们没有):

 * <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.

我确实检查了以下问题:

Why does Java’s Date.getYear() return 111 instead of 2011?

Why is the Java date API (java.util.Date, .Calendar) such a mess?

我的问题是:

> java.util.Date的原始创建者可能希望通过从中减去1900来存储“年份”的数据?特别是如果它基本上存储为长.

因此:

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?

解决方法:

基本上原始的java.util.Date设计师从C中复制了很多.你看到的是结果 – 见tm struct.所以你应该问为什么那个设计用于1900年.我怀疑根本答案是“因为我们在设计tm时不太擅长API设计.”我认为,就日期和时间而言,我们仍然不擅长API设计,因为有太多不同的用例.

这只是API,而不是java.util.Date中的存储格式.同样烦人,请注意.

标签:java,date,offset,java-util-date
来源: https://codeday.me/bug/20190714/1459362.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有