Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 = "
The specs of this audiobook are: ";
    str += "
 Title: " + title;
    str += "
 Narrator: " + narrator;
    str += "
 Year: " + year;
    str += "
 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
166 views
Welcome To Ask or Share your Answers For Others

1 Answer

getReturnDate().MONTH

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).

I think you mean

getReturnDate().get(Calendar.MONTH)

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);

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

Use a LocalDate:

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

Then access the returnDate.getMonthValue() and returnDate.getDayOfMonth() fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...