gcalan
gcalan

Reputation: 25

millisecond date is not returning expected result

For an assignment, I had to code a due date which is 30 days after the invoice date. When I run my program, I'm not getting a correct date. I'm not sure what I did wrong. Any help would be appreciated.

Code from class that creates and formats due date:

// 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());
}

Code from main class which calls the 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();
    }

Upvotes: 1

Views: 179

Answers (1)

brettw
brettw

Reputation: 11114

In general it's bad to perform date math like that, IMO. Do this:

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

Upvotes: 1

Related Questions