在java中获取开始和结束时间

在java中获取开始和结束时间,java,time,Java,Time,我想从JavaGUI到数据库获取startTime和endTime的值 电脑座位班 import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class SeatMonitoringDesign extends JFrame { publ

我想从JavaGUI到数据库获取startTime和endTime的值

电脑座位班

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class SeatMonitoringDesign extends JFrame 
{
public JLabel LStation, LID, LFirstName, LLastName, LTimeIn;
public JLabel[] Astation,Aid, Afirstname, Alastname, Atime;
public JRadioButton[] seat = new JRadioButton[10];
private String str = "";
private int station, occupiedSeatCounter;
private JLabel studNum, seatNum;
private ButtonGroup seatGroup = new ButtonGroup();
private boolean[] seatOccupied = new boolean[10];
private SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss");
private JTextField studNumTF;
private JButton logIn, logOut;
private ButtonHandler logInB;
private ButtonHandler logOutB;
private ButtonHandler radioB;


public SeatMonitoringDesign()
{

studNum = new JLabel("Enter Your Student Number: ");
studNum.setLocation(30,20);
studNum.setSize(200,100);

studNumTF = new JTextField(7);
studNumTF.setLocation(50,80);
studNumTF.setSize(120,30);

seatNum = new JLabel("Station Numbers: ");
seatNum.setLocation(60,90);
seatNum.setSize(600,400);

setTitle("Computer Seat Registration");

Container pane = getContentPane();

 pane.setLayout(null);
 pane.add(studNum);
 pane.add(studNumTF);

 setSize(1130,500);
 setResizable(false);
 setLocationRelativeTo(null);
 setDefaultCloseOperation(EXIT_ON_CLOSE);

int x=50,y=150;
for(int i=0 ; i<10 ; i++)
{
switch(i)
{
    case 0: str = "1"; break;
    case 1: str = "2"; break;
    case 2: str = "3"; break;
    case 3: str = "4"; break;
    case 4: str = "5"; break;
    case 5: str = "6"; break;
    case 6: str = "7"; break;
    case 7: str = "8"; break;
    case 8: str = "9"; break;
    case 9: str = "10"; break;
}
seat[i] = new JRadioButton(str);
seat[i].setSize(60,40);
seat[i].setLocation(x,y);
radioB = new ButtonHandler();
seat[i].addItemListener(radioB);
seat[i].setBackground(Color.green);
seatGroup.add(seat[i]);
pane.add(seat[i]);
x=110;

if((i+1)%2==0)
{
    x=50;
    y=y+30;
}
}

for(int i=0 ; i<10 ; i++)
{
seatOccupied[i] = false;
}

logIn = new JButton("Log In");
logIn.setSize(100,30);
logIn.setLocation(15,350);
logIn.setBackground(Color.orange);
logInB = new ButtonHandler();
logIn.addActionListener(logInB);
pane.add(logIn);

logOut = new JButton("Log Out");
logOut.setSize(100,30);
logOut.setLocation(125,350);
logOut.setBackground(Color.orange);
logOutB = new ButtonHandler();
logOut.addActionListener(logOutB);
pane.add(logOut);

LStation = new JLabel("Station #", SwingConstants.CENTER);
LStation.setSize(100,20);
LStation.setLocation(280,60);
pane.add(LStation);

LID = new JLabel("Student Number");
LID.setSize(100,20);
LID.setLocation(450,60);
pane.add(LID);

LFirstName = new JLabel("First Name");
LFirstName.setSize(100,20);
LFirstName.setLocation(630,60);
pane.add(LFirstName);

LLastName = new JLabel("Last Name");
LLastName.setSize(100,20);
LLastName.setLocation(810,60);
pane.add(LLastName);

LTimeIn = new JLabel("Time In");
LTimeIn.setSize(100,20);
LTimeIn.setLocation(990,60);
pane.add(LTimeIn);

Astation = new JLabel[10];
Aid = new JLabel[10];
Afirstname = new JLabel[10];
Alastname = new JLabel[10];
Atime = new JLabel[10];

y=85;
for(int i=0 ; i<10 ; i++)
{ 
switch(i)
{
    case 0: str = "1"; break;
    case 1: str = "2"; break;
    case 2: str = "3"; break;
    case 3: str = "4"; break;
    case 4: str = "5"; break;
    case 5: str = "6"; break;
    case 6: str = "7"; break;
    case 7: str = "8"; break;
    case 8: str = "9"; break;
    case 9: str = "10"; break;
}

Astation[i] = new JLabel(str, SwingConstants.CENTER);
Astation[i].setSize(100,30);
Astation[i].setLocation(280,y);
pane.add(Astation[i]);

Aid[i] = new JLabel("Vacant Station");
Aid[i].setSize(100,30);
Aid[i].setLocation(450,y);
pane.add(Aid[i]);

Afirstname[i] = new JLabel("---------");
Afirstname[i].setSize(100,30);
Afirstname[i].setLocation(630,y);
pane.add(Afirstname[i]);

Alastname[i] = new JLabel("---------");
Alastname[i].setSize(100,30);
Alastname[i].setLocation(810,y);
pane.add(Alastname[i]);

Atime[i] = new JLabel("00:00:00--");
Atime[i].setSize(100,30);
Atime[i].setLocation(990,y);
pane.add(Atime[i]);
y = y+30;
}
setVisible(true);

}

public class ButtonHandler implements ActionListener, ItemListener
{
public void itemStateChanged(ItemEvent e)
{
  for(int i=0 ; i<10 ; i++)
    {
        if(e.getSource() == seat[i])
        station = (i+1);
    }
}

public void actionPerformed(ActionEvent e)
{
LogicalChecker lc = new LogicalChecker();
cobadatabase cb = new cobadatabase(studNumTF.getText());

String output;
Date now1 = new Date();
Date now2 = new Date();

//long secs = (now2.getTime() - now1.getTime()) / 1000;
//long diffSeconds = diff / 1000 % 60; 
//long diffMinutes = diff / (60 * 1000) % 60; 
// long diffHours = diff / (60 * 60 * 1000) % 60;

//long startTime = System.currentTimeMillis();
//long finishTime = System.currentTimeMillis();
//long elapsedTime = finishTime - startTime; 

long diff = (now2.getTime() - now1.getTime());
cobadatabase cb2 = new       cobadatabase(studNumTF.getText(),dateFormatter.format(now1),dateFormatter.format(now2),      diff);


if("Log In".equals(e.getActionCommand()))
{         
    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("Log Out".equals(e.getActionCommand()))
 {


    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: "     +diff;
        JOptionPane.showMessageDialog(null,output, "Check-    Out.",JOptionPane.INFORMATION_MESSAGE);

    }
}

}
} 

} 

这里的问题是,当单击登录按钮时,开始时间同时显示在我的数据库的startTime和endTime列上。单击“注销”按钮时,会在数据库中创建另一行,其中包含startTime和endTime列上的endTime。。我想知道为什么会发生这种情况。

您应该尝试设置单击正确按钮的时间,而不是设置同一按钮的开始和结束时间。我会为startTime设置一个全局变量,然后像这样计算

private long startTime = null;
public void actionPerformed(ActionEvent e) {
    LogicalChecker lc = new LogicalChecker();
    cobadatabase cb = new cobadatabase(studNumTF.getText());

    String output;


    //long secs = (now2.getTime() - now1.getTime()) / 1000;
    //long diffSeconds = diff / 1000 % 60; 
    //long diffMinutes = diff / (60 * 1000) % 60; 
    // long diffHours = diff / (60 * 60 * 1000) % 60;

    //long startTime = System.currentTimeMillis();
    //long finishTime = System.currentTimeMillis();
    //long elapsedTime = finishTime - startTime; 

    long diff = (now2.getTime() - now1.getTime());
    cobadatabase cb2 = new cobadatabase(studNumTF.getText(),dateFormatter.format(now1),dateFormatter.format(now2),     diff);


    if("Log In".equals(e.getActionCommand())){    
         this.startTime = new Date().getTime(); // set start time
         ... do stuff
    } else if("Log Out".equals(e.getActionCommand())){   
         long totalTime =  new Date().getTime() - this.startTime(); // calculate total time
         ... do stuff

    }
}
请看下面的URL 在应用程序开始和结束时使用它

如果你在测量时间,看看应用程序执行了多长时间,我猜上面的不是最好的。在这种情况下,请尝试以下方法

import java.util.*;

public class VectorTest
{
    Vector v = new Vector();

    public VectorTest()
    {
        long startTime = System.currentTimeMillis(); // Get the start Time
        long endTime = 0;

       System.out.println( startTime);

       for(int i=0;i<100000;i++)
       {
           v.add(i);
       }

        for(int i=0;i<v.size();i++)
        {
            System.out.println(v.get(i));
        }
        endTime = System.currentTimeMillis(); //Get the end Time

        System.out.println(endTime);

        System.out.println("Difference in mili seconds: "+ (endTime-startTime)); //Print the difference in mili seconds
        System.out.println("Differencce in Seconds: "+ (endTime-startTime)/1000); // Print the difference in seconds

    }

    public static void main(String[]args)
    {
        new VectorTest();
    }
}
import java.util.*;
公共类向量测试
{
向量v=新向量();
公共矢量测试()
{
long startTime=System.currentTimeMillis();//获取开始时间
长结束时间=0;
系统输出打印LN(开始时间);

对于(int i=0;我不明白……您将依次初始化
now1
now2
,因此它们很有可能表示完全相同的日期/时间(因为它们仅精确到毫秒)。在完成要测量的操作后,是否应该初始化后者?当需要在Java应用程序中测量时间时,可以使用
System.nanotime()
,它比使用
日期
差异更准确。@Abu,为什么不使用前者的具体原因是什么?我认为这是对付NPE更简单的方法。@Mark Peters我应该把now1和now2放在哪里?我同意@MarkPeters的观点,你对时间变量的初始化总是会给你时间上的差异创建2个日期对象并检索它们的时间需要花费大量时间。这就是为什么开始时间是startTime和endTime。另外,我们需要更多的代码/信息来帮助您完成其余的工作,您所说的数据库是什么意思?您在哪里将数据插入数据库?我想做的是在数据库中的startTime列中存储开始时间单击“登录”按钮,然后,当用户注销时,时间将存储到我的数据库中的endTime列中。没问题。这将起作用。或者链接将起作用(根据您的要求。我的示例返回秒,链接以dd:mm:yy格式提供返回时间的示例)。在执行actionPerformed()后立即查找开始时间方法被调用。查找注销方法被调用的结束时间(在方法的末尾)。感叹它仍然是一样的。嗯。我所做的是在登录验证和dateFormatter.format(now1)之前放置dateFormatter.format(now1);在注销验证之后。发生的是,它在数据库中的我的表中显示了4行。:(你的问题是关于时间的,而不是关于数据库的问题。我相信这里的建议对于时间问题来说已经足够了。如果在向数据库插入数据时有任何错误,请打开一个单独的问题。我感谢这个建议。但我认为这段代码不适用于我制作的类。如果你非常友好,请请看一看我最近编辑的类。我想做的是只将开始时间和结束时间添加到一行。我真的很难做到这一点。我真的需要帮助。
import java.util.*;

public class VectorTest
{
    Vector v = new Vector();

    public VectorTest()
    {
        long startTime = System.currentTimeMillis(); // Get the start Time
        long endTime = 0;

       System.out.println( startTime);

       for(int i=0;i<100000;i++)
       {
           v.add(i);
       }

        for(int i=0;i<v.size();i++)
        {
            System.out.println(v.get(i));
        }
        endTime = System.currentTimeMillis(); //Get the end Time

        System.out.println(endTime);

        System.out.println("Difference in mili seconds: "+ (endTime-startTime)); //Print the difference in mili seconds
        System.out.println("Differencce in Seconds: "+ (endTime-startTime)/1000); // Print the difference in seconds

    }

    public static void main(String[]args)
    {
        new VectorTest();
    }
}