无法向日历添加天数

0 java calendar date

我正在尝试写一些允许某人在课堂上查看有声读物的内容,并且应该在14天之后设置截止日期.我的类有一个toString()方法,它应该打印出截止日期,但是无论如何都会一直打印出3/5.

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;
}
Run Code Online (Sandbox Code Playgroud)

And*_*ner 6

getReturnDate().MONTH
Run Code Online (Sandbox Code Playgroud)

不是做你的意思.它的值是Calendar.MONTH静态常量的值,我想这是2(实际上,你可以看到它在源中).

我想你的意思是

getReturnDate().get(Calendar.MONTH)
Run Code Online (Sandbox Code Playgroud)

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

Calendar returnDate = getReturnDate();
// ...
str += "Due date " + (returnDate.get(Calendar.MONTH) + 1) + "/" + returnDate.get(Calendar.DATE);
Run Code Online (Sandbox Code Playgroud)

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

使用LocalDate:

LocalDate returnDate = LocalDate.now().plusDays(14);
Run Code Online (Sandbox Code Playgroud)

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