【问题标题】:Android: calender not give the Full Year number and gives only 111 instead of the 2011Android:日历不给出全年数字,只给出 111 而不是 2011
【发布时间】:2011-12-29 04:45:23
【问题描述】:

我正在使用此代码获取当前设备时间的年份:

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.getTime().getYear();

但是我得到的是 111 而不是当年的 2011 年。

如果我将 2012 年设置为当前年份,那么它会给我 112 而不是 2012 年。

为什么会这样? 请帮助我。 谢谢。

【问题讨论】:

    标签: time android-emulator emulation android


    【解决方案1】:

    getYear() 返回自 1900 年以来的年份。所以你必须使用

    cal.getTime().getYear() + 1900
    

    编辑

    Date.getYear() 已弃用。所以你可以使用cal.get(Calendar.YEAR) 来获取年份字段。见Date.getYear()Calendar.get()

    【讨论】:

    • +1。 “返回此 Date 对象自 1900 年以来的公历年。”不过,您确实应该改用cal.get(Calendar.YEAR) - 1900-
    • 谢谢@Michell,我编辑了我的答案。事实上,他希望将年份作为 2011 年本身。所以不需要用 1900 减法。
    • 好的,谢谢两位的回复。
    • 此方法已弃用。使用 Calendar.get(Calendar.YEAR) - 1900 返回此 Date 对象自 1900 年以来的公历年份。所以这是真的
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2019-10-29
    • 2013-03-05
    • 2012-12-19
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多