无法将天数添加到日历 [英] Can't add days to Calendar

查看:85
本文介绍了无法将天数添加到日历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试写一些允许某人将有声读物上课的书,并且应将到期日设置为14天。我的班级有一个toString()方法,该方法应打印出到期日,但无论如何始终打印出到期日是3/5。

I am trying to write something that allows someone to check an audio book out for class, and it should set a due date for 14 days later. My class has a toString() method that should print out the due date, but consistently prints out that it is due 3/5 no matter what.

public String toString() // Prints specs of a Book object
{
    String str = "\nThe specs of this audiobook are: ";
    str += "\n\t Title: " + title;
    str += "\n\t Narrator: " + narrator;
    str += "\n\t Year: " + year;
    str += "\n\t Due Date: " + (getReturnDate().MONTH + 1) + "/" + getReturnDate().DATE;
    return str;
}
public Calendar getReturnDate() // Makes return date 14 days after today
{
    Calendar duedate = Calendar.getInstance();
    duedate.add(Calendar.DAY_OF_YEAR, 14);
    return duedate;
}


推荐答案

getReturnDate().MONTH

没有按照您的意思去做。它的值是 Calendar.MONTH 静态常量的值,我想是2(实际上,您可以看到它是源中)。

Isn't doing what you mean. Its value is the value of the Calendar.MONTH static constant, which is, I suppose, 2 (indeed, you can see it is in the source).

我想你是说

getReturnDate().get(Calendar.MONTH)

此外,您不应该调用 getReturnDate()两次:如果两次调用,日期可能会不一致。调用一次,将其分配给一个字段:

Additionally, you shouldn't be calling getReturnDate() twice: you might get inconsistent dates if you call it twice. Call it once, assign it to a field:

Calendar returnDate = getReturnDate();
// ...
str += "Due date " + (returnDate.get(Calendar.MONTH) + 1) + "/" + returnDate.get(Calendar.DATE);






但实际上更好的解决方案是使用这些旧的,有效弃用的API。


But in fact a better solution would be not to use these old, effectively-deprecated APIs.

使用 LocalDate

LocalDate returnDate = LocalDate.now().plusDays(14);

然后访问 returnDate.getMonthValue() returnDate.getDayOfMonth()字段。

这篇关于无法将天数添加到日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆