我正在开发一个程序,它将是一个基本功能,如果用户可以检查一些东西,程序将计算一个截止日期,为了简单起见,将在七天后。 此函数在其他类中使用,现在已在使用它的类中定义
today=Calendar.getInstance();
我正在使用Calendar类来执行此操作。 起初我试过这个
public Calendar getReturnDate()
{
Calendar dueDate = Calendar.getInstance();
dueDate.set(today.MONTH, today.get(today.MONTH));
dueDate.set(today.YEAR, today.get(today.YEAR));
dueDate.add(today.DATE,today.get(today.DATE + 7));
return dueDate;
}
这给了我一个结果,一切都打印到毫秒。
所以我研究了Calendar类,发现.add
方法可以完成这个工作......或者我认为。以下是代码
public Calendar getReturnDate()
{
Calendar dueDate = Calendar.getInstance();
dueDate.set(today.MONTH, today.get(today.MONTH));
dueDate.set(today.YEAR, today.get(today.YEAR));
dueDate.add(today.DATE,7);
return dueDate;
}
在以下代码中调用该函数时,将发生以下打印。
public String toString()
{
//Prints them out
String str = "The specs of the book are: ";
str+= "\n\t Title: " + title;
str+= "\n\t Author: " + year;
str += "\n\t checkout date: " + (getReturnDate().MONTH+1) + "/" + getReturnDate().DATE;
return str;
}
结果:
Title: ABC
Author: Suzie Smith
checkout date: java.util.GregorianCalendar[time=1428600973310,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/New_York",offset=-18000000,dstSavings=3600000,useDaylight=true,transitions=235,lastRule=java.util.SimpleTimeZone[id=America/New_York,offset=-18000000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=3,WEEK_OF_YEAR=15,WEEK_OF_MONTH=2,DAY_OF_MONTH=9,DAY_OF_YEAR=99,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=36,SECOND=13,MILLISECOND=310,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
正如您所看到的,这是无法正常运行的。我想在上面的代码中调用此方法时打印出月/年。
有人知道怎么做或为什么我的工作不起作用?
来源: https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html
答案 0 :(得分:0)
public String toString() {
Calendar returnDate = getReturnDate();
// Prints them out
String str = "The specs of the book are: ";
str += "\n\t Title: " + title;
str += "\n\t Author: " + year;
str += "\n\t checkout date: " + (returnDate.get(Calendar.MONTH) + 1) + "/" + returnDate.get(Calendar.DATE);
return str;
}