在android中的Calendar对象中只返回默认值.为什么?



我用这种方式为日历对象设置了一个日期。。。

Calendar lastCheckUp = Calendar.getInstance();
lastCheckUp.set(year, month+1, day);

现在,当我使用在控制台中打印出来时

System.out.println(lastCheckUp);

我得到了正确的值。。。

07-18 11:59:13.903: I/System.out(1717): java.util.GregorianCalendar[time=1365834504001,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=13,DAY_OF_YEAR=103,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=2,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=58,SECOND=24,MILLISECOND=1,ZONE_OFFSET=19800000,DST_OFFSET=0]

所以我假设所有的值都在日历对象中设置正确。

但当我尝试使用访问它时

mTextViewLastCheckDate.setText(new StringBuilder().append(lastCheckUp.DAY_OF_MONTH)
            .append("/").append(lastCheckUp.MONTH).append("/").append(lastCheckUp.YEAR)
            .append(" "));

我只得到默认值。。。

也就是说,我的文本视图给出了5/2/1 的输出

我做错了什么?

您使用的是lastCheckup.MONTHlastCheckup.DAY_OF_MONTH等。这些是常量字段-要访问特定日历的值,您需要

int month = lastCheckUp.get(Calendar.MONTH);

等等。阅读Calendar的文档,了解有关如何使用它的更多详细信息。

然而,您还需要了解,在Calendar中,月份是基于0的,所以它看起来仍然不正确。此外,你几乎可以肯定地想要0填充日期和月份。使用SimpleDateFormat为您做这件事会更好。

// Not sure why you want a space at the end, but...
DateFormat format = new SimpleDateFormat("dd/MM/yyyy ");
mTextViewLastCheckDate.setText(format.format(lastCheckup.getTime());

您还应该考虑要使用哪个时区和区域设置。上面的代码只是使用默认值。

编辑:注意这一行:

lastCheckUp.set(year, month+1, day);

几乎可以肯定是错误的。我们不知道month在这里的真正含义,但在set调用中,它应该在0-11(包括0-11)的范围内(假设公历)。

您的问题是如何访问Calendarget方法以及对Calendar常量的引用。

试试这个:

mTextViewLastCheckDate.setText(
  new StringBuilder().append(lastCheckUp.get(Calendar.DAY_OF_MONTH))              
  .append("/")
  .append(lastCheckUp.get(Calendar.MONTH)) // beware, Calendar months are 0 based
  // please refer to Jon Skeet's solution for a better print out of your date
  // or add +1 to the month value here, instead of setting your Calendar with month + 1. 
  // Otherwise December will not work. See also comments below. 
  .append("/")
  .append(lastCheckUp.get(Calendar.YEAR))
  .append(" ")
);

顺便说一句,当您试图从类的实例访问类的常量时,大多数IDE都会警告您。这可以帮助你找出你通常做错了什么。

最新更新