问候!我编写了以下代码,预计可以处理该程序。如果用户手动给出的到期日期早于当前日期,则程序应终止,否则程序显示剩余期限。
当我输入到期日期作为当前日期时,即年:2014 年,月:3,日:7 按照我的预期,该计划应该已经终止,但它显示为 1 年等......剩余。我哪里做错了。
// Sets GregorianCalendar expiryDate object
static void setTrial(){
System.out.println("\n----- SET TRIAL DATE ----\n");
System.out.print("Year : ");
int year = new Scanner(System.in).nextInt();
System.out.print("Month : ");
int month = new Scanner(System.in).nextInt();
System.out.print("Day : ");
int day = new Scanner(System.in).nextInt();
expiryDate = new GregorianCalendar(year, month, day);
}
// Validates the expiryDate with current GregorianCalendar object
static void validate(){
System.out.print("\n----- VALIDATING THE PRODUCT ----\n");
GregorianCalendar current = new GregorianCalendar();
if( current.after(expiryDate) ){
System.out.println("\nYour trial period is expired. Please buy the product.");
}else{
GregorianCalendar temp = new GregorianCalendar(expiryDate.get(GregorianCalendar.YEAR) -
current.get(GregorianCalendar.YEAR),
expiryDate.get(GregorianCalendar.MONTH) -
current.get(GregorianCalendar.MONTH),
expiryDate.get(GregorianCalendar.DAY_OF_MONTH) -
current.get(GregorianCalendar.DAY_OF_MONTH));
System.out.println("\nYou still have " +
temp.get(GregorianCalendar.YEAR) + " years, " +
temp.get(GregorianCalendar.MONTH) + " months, " +
temp.get(GregorianCalendar.DAY_OF_MONTH) +
" days remaining... \n\nPlease buy the product before it expires!");
}
最佳答案
月份从 0(一月)到 11(十二月)开始。
所以你需要这样做:
expiryDate = new GregorianCalendar(year, month-1, day);
另请注意,GregorianCalendar 没有 0 年(根据 definition Wikipedia gives ),这就是原因
System.out.println(new GregorianCalendar(0, 3, 8).get(GregorianCalendar.YEAR));
将打印 1。
相反,你可以这样做:
int yearsRemaining = expiryDate.get(GregorianCalendar.YEAR) - current.get(GregorianCalendar.YEAR);
关于java - 产品有效期(意外输出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22252514/