user3474852
user3474852

Reputation: 27

Wrong time is displayed after date math

I have an application that tracks the wait time of a customer in a restaurant. It simply subtracts the time the customer began waiting from the current time, then formats it with StandardDateFormat into hh:mm and displays it as a string.

The problem is that the timer always begins with 6 hours, such as 06:01.

    ActionListener actListner = new ActionListener() 
    {
        public void actionPerformed(ActionEvent event) 
        {
            aTable.updateTime();
        }
    };

    Timer timer = new Timer(1000, actListner);
    timer.start();
}

This is in the main program

public void updateTime()
{
    data.updateTime();
    fireTableDataChanged();
    fireTableRowsInserted(data.name.size() - 1, data.name.size() - 1);
}

This is in the table model

public void updateTime()
{
    Date newTime = new Date();

    for (int i = 0; i < startTime.size(); i++)
    {                  
        this.setTimeWaiting(i, hoursMin.format(new Date(newTime.getTime() - startTime.get(i).getTime())));  
    }
}

public void setTimeWaiting(int index, Object newVar)
{
    timeWaiting.remove(index);
    timeWaiting.add(index, newVar.toString());
}

This is in the data model.

Every time a new row is added it puts the time the row is added in one column then the time that person has been waiting in the other column, but the waiting column is 6 hours ahead. It otherwise works fine.

Upvotes: 0

Views: 59

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101820

As k_g says, this is almost certainly a time zone issue. You are getting funny results because the Date class is intended for absolute times, not intervals.

I would recommend you use a library like Joda Time. It has special classes for concepts such as Intervals and Durations.

Or if you are using JDK 8 you can use the new date/time classes that have just been introduced.

Upvotes: 1

k_g
k_g

Reputation: 4464

This sounds like a timezone issue. Maybe you should set the timezone for the date format to UTC.

Upvotes: 1

Related Questions