我正在制作一个小游戏。当游戏第一次开始时,我在 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 开始,这是 Calendar
和 Date
所共有的。
关于java - Calendar.getTime().getYear() 返回 0113 而不是 2013,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15769882/