【问题标题】:Implementing correct date using Calendar into Android app在 Android 应用中使用日历实现正确的日期
【发布时间】:2013-04-02 13:36:42
【问题描述】:

我在尝试让日期在我的应用程序中正确显示时遇到了麻烦,这里是代码

//i declare the calendar called now
private Calendar now;

//i set up the calendar with what i believe could be the problem in setting up the wrong date
now = Calendar.getInstance();
    now.set(Calendar.MONTH, Calendar.MONTH);
    now.set(Calendar.DAY_OF_MONTH, Calendar.DAY_OF_MONTH);
    now.set(Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK);

//whatDay being a textview, is asked to display the date
whatDay.setText(DateFormat.format("E, dd MMMM", now));

目前,就显示日期而言,一切正常 - 只是显示了错误的日期,这有点问题

【问题讨论】:

标签: java android parsing date calendar


【解决方案1】:

你可以这样做

Calendar now = Calendar.getInstance();
now.set(MONTH, SEPTEMBER);
now.set(DAY_OF_MONTH, 22);
now.set(DAY_OF_WEEK, MONDAY);

您可以在代码中获取第二个参数的值。然后使用DateFormat 格式化now 并将其添加到您的TextView

Calendar Docs

编辑

我不知道您是如何获得日期的,但您可以在代码中设置 Constants,例如 MONTH、DAY 等...您可以在解析文件时以任何您想要的方式进行初始化,然后使用这些在Calendarset 方法中。还有一个add 方法Calendar that will add to the field values (MONTH, DAY_OF_WEEK, etc...) instead of setting them to the value in your secondparam`。您还可以在我上面链接的文档中找到其他有用的方法。让我知道这是否适合您。

您正在为第二个param 使用field 值。看看你的做法与我的不同。另外,See this link 作为要输入的值的示例。

【讨论】:

  • 我只是使用那个日期作为布局的一个例子,我如何将它与今天的日期一起使用?
  • 我明白这一点,但这是我对你的代码所能做的最好的事情。这就是Calendar.getInstance() 返回的内容。然后,如果您需要设置不同的日期,您可以添加所需的任何属性
  • 似乎无法使其正常工作,错误行显示在上述参数中的对象下方。我将添加更多代码
  • 我们正在取得进展,但有哪些错误?你导入日历了吗?此外,您可能需要将其更改为 Calendar.MONTH 等。试试看。希望这会有所帮助
  • 似乎认为它的星期六是 3 月 2 日,这是我写的
猜你喜欢
  • 1970-01-01
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多