有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java日历。getTime()。getYear()返回0113而不是2013

我在做一个小游戏。当游戏第一次开始时,我在SharedReferences中以秒为单位保存自1970年1月1日以来的时间

现在我想在我的屏幕上以这种形式给出这个日期:DD.MM。YYYY

我使用了日历功能,但它返回02.04.0113,因此,缺少1900年

这是我的密码:

private void initBornTXT() {
    SharedPreferences pref = getSharedPreferences("LIFE", 0);
    long born = pref.getLong("BIRTHDAY", 0);
    Calendar c = Calendar.getInstance();

    c.setTimeInMillis(0);

    c.add(Calendar.SECOND, (int)born);
    int year = c.getTime().getYear();
    int month = c.getTime().getMonth();
    int day = c.getTime().getDay();
    String string_born = String.format("%02d.%02d.%04d", day, month, year);
    TextView born_txt = (TextView)findViewById(R.id.textViewBorn);
    born_txt.setText(string_born);
}

有什么不对的


共 (3) 个答案

  1. # 1 楼答案

    您使用的是getTime,它返回一个日期对象。日期基于0=1900。这就是预期的产出。改用SimpleDataFormat

    但制造了一个Y2K漏洞,这是值得称赞的:)

  2. # 2 楼答案

    这是正常的,有记录的行为。有关Date#getYear(),请参见JavaDoc

    获得这一年的更好方式是:

    c.get(Calendar.YEAR)

  3. # 3 楼答案

    没什么问题。您只是没有查看正在调用的方法的文档,^{}

    Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

    请注意,您应该收到一条警告,说明您正在使用不推荐使用的API:不要忽略这些警告

    另外,帮自己一个忙,不要自己格式化:使用SimpleDateFormat。(或者理想情况下,使用Joda Time代替…)这样你就可以避免也是错误的。。。你可能没有注意到,由于月份以0为基础,你休息了一个月,这对CalendarDate都很常见