【问题标题】:SimpleDateFormat subclass adds 1900 to the yearSimpleDateFormat 子类将 1900 添加到年份
【发布时间】:2012-04-02 19:26:03
【问题描述】:

我创建了SimpleDateFormat 的几个子类,以简化处理我在 Android 上与之交谈的 Azure 提要。其中之一如下:

public class ISO8601TLDateFormat extends SimpleDateFormat {

    private static String mISO8601T = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

    public ISO8601TLDateFormat() {
        super(mISO8601T);
    }

    public ISO8601TLDateFormat(Locale inLocale) {
        super(mISO8601T, inLocale);
    }
}

如您所见,其目的是生成或解释看起来像的日期

2012-03-17T00:00:00.000+0100

这是 Azure 服务所期望的。但是,当我输入从 DatePicker 构造的 Date 对象时:

mDate = new Date(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth());

ISO8601TLDateFormat 的输出是

3912-03-17T00:00:00.000+0100

如您所见,这一年比我或其他任何不未来的人都需要多 1900 年。我在 Date 对象到 Azure 提要系统的整个过程中仔细检查了它,它报告它的日期是 2012 年,这是我所期望的。为什么SimpleDateFormat 坏了?

【问题讨论】:

  • 可能有一个Date参与某处,因为它的年份是 1900 年。
  • 我认为这里没有足够的信息......我们需要知道您对 SimpleDateFormat 进行的具体调用,以产生错误的输出以及它是如何被初始化的等等。
  • 我已经得到了答案(如下),但我会澄清我是如何错误地构造了我的 Date 对象。

标签: android date datepicker


【解决方案1】:

问题是Date 的构造函数没有收到你所期望的。取自javadocumentation

public Date(int year,
            int month,
            int date)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year - the year minus 1900.
month - the month between 0-11.
date - the day of the month between 1-31.

您需要记住,您构造了一个日期,0, 0, 1 是 1900 年 1 月 1 日。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
  • 2011-07-07
  • 2020-11-11
相关资源
最近更新 更多