【问题标题】:Why the current year in the date saved as 3912?为什么将日期中的当前年份保存为 3912?
【发布时间】:2012-01-31 08:19:03
【问题描述】:

获取当前日期和时间

final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);

创建当前日期对象

Date toDate;
     toDate.setYear(mYear);
     toDate.setMonth(mMonth);
     toDate.setDate(mDay);



Date endDate = toDate;

打印 endDate 对象时我得到了

Mon Jan 01 13:11:00 GMT+03:00 3912

为什么?

【问题讨论】:

  • 您的系统时间是否设置为正确的年份?
  • y2.012K 错误导致问题

标签: android date calendar


【解决方案1】:

来自Date.setYear(int) 描述:为此 Date 对象设置自 1900 年以来的公历年。因此,1900 + 2012 = 3912

但是calendar.get(Calendar.YEAR) 返回确切的年份编号2012。因此,API 的这种不一致会导致您的问题。但无论如何Date.setYear(int) 已被弃用,因此,最好使用Calendar 对象进行日期计算。

【讨论】:

  • @AdhamEnaya 您可以从年份编号中减去1900toDate.setYear(mYear - 1900)。但我最好建议使用Calendar 对象进行日期计算。
【解决方案2】:

更好地使用日历

Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,myear);

(即)

cal.set(Calendar.YEAR,2016);

【讨论】:

    猜你喜欢
    • 2013-03-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2020-11-11
    • 2020-05-26
    相关资源
    最近更新 更多