毫秒日期未返回预期结果

时间:2012-02-15 01:55:02

标签: java

对于作业,我必须在发票日期后30天编制截止日期。当我运行我的程序时,我没有得到正确的日期。我不确定我做错了什么。任何帮助将不胜感激。

创建和格式化截止日期的类的代码:

// a method that returns the due date
public Date getDueDate()
{
    Date dueDate = new Date(invoiceDate.getTime() +
            (30 * 24 * 60 * 60 * 1000));
    return dueDate;
}

// a method that returns the formatted due date
public String getFormattedDueDate()
{
    DateFormat shortDueDate  = DateFormat.getDateInstance(DateFormat.SHORT);
    return shortDueDate.format(this.getDueDate());
}

调用getFormattedDueDate的主类中的代码:

public static void displayInvoices()
{
    System.out.println("You entered the following invoices:\n");
    System.out.println("Number\tTotal\tInvoice Date\tDue Date");
    System.out.println("------\t-----\t------------\t--------");
    double batchTotal = 0;
    int invoiceNumber = 1;
    while (invoices.size() > 0)
    {
        Invoice invoice = invoices.pull();
        System.out.println(invoiceNumber + "\t     " + invoice.getFormattedTotal()
                + "       " + invoice.getFormattedDate()
                + "\t     " + invoice.getFormattedDueDate());

        invoiceNumber++;
        batchTotal += invoice.getInvoiceTotal();
    }

1 个答案:

答案 0 :(得分:1)

一般来说,执行日期数学是很糟糕的,IMO。这样做:

public Date getDueDate() {
   Calendar cal = Calendar.getInstance();
   cal.setTime(invoiceDate);
   cal.add(Calendar.DAY_OF_MONTH, 30);
   return cal.getTime();
}
相关问题