如何在java中获取totalTime?

时间:2012-10-07 21:59:59

标签: java time

我在这里读了很多关于获得totalTime的答案。我尝试将我找到的代码应用到我的代码中:

long secs = (dateFormatter.format(now2) - dateFormatter.format(now1)) / 1000;
int hours = secs / 3600;
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;

我的代码:

 public void actionPerformed(ActionEvent e)
 {
 LogicalChecker lc = new LogicalChecker();
 Date now1 = new Date();
 Date now2 = new Date();
 cobadatabase cb = new cobadatabase(studNumTF.getText());
 String output;

  if(e.getActionCommand() == "Log In")
    {
        if(station == 0)
        {
            lc.StationCheck(0);
        }
        else if(seatOccupied[station-1] == true)
        {
            lc.StationCheck(2);
        }
        else if(!studNumTF.getText().equals(cb.getStudentNumber()))
        {
             studNumTF.setText("");
             lc.StationCheck(3); 
        }
        else
        {
            seatOccupied[station-1] = true;


                Aid[station-1].setText(cb.getStudentNumber());
                Afirstname[station-1].setText(cb.getFirstName());
                Alastname[station-1].setText(cb.getLastName());  
                seat[station-1].setBackground(Color.red);
                Atime[station-1].setText(dateFormatter.format(now1));
                occupiedSeatCounter++;


        }
    }

  if(e.getActionCommand() == "Log Out")
    {
        if(station == 0)
        {
            lc.StationCheck(0);
        }
        else if(Aid[station-1].getText() == "Vacant Station")
        {
            lc.StationCheck(1);
        }
        else
        {

            Aid[station-1].setText("Vacant Station");
            Afirstname[station-1].setText("---------");
            Alastname[station-1].setText("---------");
            seat[station-1].setBackground(Color.green);
            Atime[station-1].setText("00:00:00");
            seatOccupied[station-1] = false;
            studNumTF.setText("");
            output = "Time Check-Out "+dateFormatter.format(now2)+"\n Total Time: ";
            JOptionPane.showMessageDialog(null,output, "Check-Out.",JOptionPane.INFORMATION_MESSAGE);

        }
}

}

但是它给出了一个错误,表示运算符不能应用于java.lang.String。我不知道如何获取它的总时间并将其显示给我创建的JOptionPane。我真的需要帮助。

1 个答案:

答案 0 :(得分:1)

你的问题在这里:dateFormatter.format(now2) - dateFormatter.format(now1)因为像@Luiggi所说格式返回一个字符串。您应该执行以下操作:now2.getTime() - now1.getTime()以获得以毫秒为单位的差异。