产品有效期(意外产出)

时间:2014-03-07 14:16:47

标签: java calendar

电贺!我已经编写了一个以下代码,该代码有望处理该程序。如果用户手动提供的到期日期在当前日期之前,程序应该终止,否则程序会显示剩余的时间。

当我输入到期日作为当前日期,即年份: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!");
    }

2 个答案:

答案 0 :(得分:2)

月份从0(1月)到11(12月)开始。

所以你需要这样做:

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

答案 1 :(得分:1)

更改以下内容

expiryDate = new GregorianCalendar(year, month, day);

GregorianCalendar expiryDate = new GregorianCalendar(year, month-1, day);

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

System.out.println("\nYou still have " + temp.get(GregorianCalendar.YEAR-1) + " years, " + temp.get(GregorianCalendar.MONTH) + " months, " + temp.get(GregorianCalendar.DAY_OF_MONTH) + " days remaining... \n\nPlease buy the product before it expires!");