java - Calendar.getTime().getYear() 返回 0113 而不是 2013

标签 java android calendar

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

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

我使用了日历功能,但它返回 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);
}

可能出了什么问题?

最佳答案

没什么问题。您只是没有查看您正在调用的方法的文档,Date.getYear() :

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 所共有的。

关于java - Calendar.getTime().getYear() 返回 0113 而不是 2013,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769882/

相关文章:

java - 如何更正 EST 格式的日期?

java - 将 Log4j 日志记录添加到 Vaadin 8 应用程序

android - 无法在 Eclipse 的 SQLite 管理器插件中打开数据库文件?

java - 将在线 XML 数据设置/传递到表格布局中的图像按钮的逻辑

java - Spring Data JPA 无法确定属于同一类对象的属性的类型

java - 如何创建通用的 FlatFileItemReader 来读取具有不同标题的 CSV 文件?

安卓碰撞检测精度

javascript - fullCalendar - 带有颜色选项的 addEventSource

java - 在android中转换日期格式?

php - 如何使事件永久保留在全日历中