当前位置: 首页 > 知识库问答 >
问题:

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

松旻
2023-03-14

我想从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);

    }
}

}
} 

} 

Cobadatabase类

import java.sql.*;
import java.util.*;
import java.text.*;

public class cobadatabase{
protected String sn,fn,ln,srt, sn2, srt2, et;
protected Long tt;
private Connection conn;
private PreparedStatement st; 

public cobadatabase(){
    try{
       Class.forName("com.mysql.jdbc.Driver");
       conn =   DriverManager.getConnection("jdbc:mysql://localhost/studentrecords","root","");

        }

catch(Exception e){}
}

 public cobadatabase(String sn2, String str2, String et, long tt)
{
    this();
    try
    {
    st = conn.prepareStatement("Insert into time(StudentNumber,StartTime,EndTime,TotalTime) values(?,?,?,?)");
    st.setString(1,sn2);
    st.setString(2,str2);
    st.setString(3,et);
    st.setLong(4,tt);
    st.executeUpdate();

}
catch(Exception e){}
}

public cobadatabase(String StudentNumber)
{

    this();
    try{
       st = conn.prepareStatement("SELECT * FROM student WHERE StudentNumber=?");
       st.setString(1,StudentNumber);
       ResultSet rs = st.executeQuery();

            while (rs.next())
            {
                this.sn = rs.getString(1);
                this.fn = rs.getString(2);
                this.ln = rs.getString(3);
                this.srt = rs.getString(4);

                SimpleDateFormat ft = new SimpleDateFormat("kk:mm:ss");
                ft.format(rs.getTime("TotalTime").getTime());
            }   
}
catch(Exception e){}
}

public cobadatabase(String StudentNumber2, String Start, String End)
{

    this();
    try{
       st = conn.prepareStatement("SELECT * FROM time WHERE StudentNumber2=?");
       st.setString(2,Start);
       st.setString(3,End);
       ResultSet rs = st.executeQuery();
            while (rs.next())
            {
                this.sn2 = rs.getString(1);
                this.srt2 = rs.getString(2);
                this.et = rs.getString(3);
                this.tt = rs.getLong(4);
            }
    }
    catch(Exception e){}
}



    public String getFirstName(){
    return fn;
}
    public String getLastName(){
    return ln;
}
    public String getStudentNumber(){
    return sn;
}
    public String getStart(){
    return srt2;
}
    public String getEnd(){
    return et;
}

}

这里的问题是,当单击登录按钮时,开始时间显示在我的数据库中的开始时间和结束时间列上。当单击注销按钮时,将在数据库中创建另一个行,该行在starTime和endTime列上都包含endTime。我想知道为什么会这样...

共有2个答案

冯和硕
2023-03-14

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

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

    }
}
暨修洁
2023-03-14

请看下面的URLhttp://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/ 在应用程序开始和结束时使用它。

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

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

关于良好编程实践的额外建议

>

  • 看看第三个重载的“CodeBase”构造函数。SQL查询中有1个参数,但试图在程序中设置2,即使索引2和3无效

    关闭最终块内的连接

    不要将catch()方法保留为空。打印堆栈跟踪

    不要在任何地方都使用相同的准备语句。将它们包装为局部变量,而不是全局变量。有时数据库中的自动连接关闭方法会出现延迟。在这种情况下,您的程序将以意外的方式运行。如果您在本地声明它们,那么一旦该方法被禁用,变量就会消失

  •  类似资料:
    • 我有一个enum,其值如下:,,等。 我试图编写一个方法,它接受并返回该时间段的开始和结束日期。 我研究了新的Java8类,该类可能需要一个开始时间和结束时间,但似乎没有任何干净的方法可以在之后检索这些值。 如果不使用(似乎是错误的数据结构)或一些难看的日期时间算法,我如何能一次干净地返回开始日期和结束日期?

    • 问题内容: 我想知道如何计算本周的开始和结束日期?我发现这不是在标准android库或date4j之类的库中实现的。 是否有一些简单明了的实现方法?还是我必须再次骑自行车? 谢谢。 问题答案: 也许MonthDisplayHelper可能对您有所帮助。 祝好运!

    • 问题内容: 我有这样的时间戳字符串: 我想对它们进行排序,以便可以从上述时间戳获取起始范围和终止范围。我正在做如下: 这将为我提供上述时间戳列表的开始和结束范围。这是正确的方法还是有更好的方法? 更新资料 因此,我应该执行以下操作: 问题答案: 将那些ISO 8601 字符串解析为对象。 将这些日期时间对象添加到并排序。您可能想要诸如或。 java.time类实现该方法,以作为实现合同。因此,这些

    • 我的日期格式为:YYYY-MM-DD 所需的输出格式是:"yyyy-MM-dd'T'HH: mm: ss.SSS'Z'" 我想在美国/芝加哥时区获得ISO格式的日期,作为一天的开始时间(从上午12:00开始)和一天的结束时间(结束于晚上11:59)。 对于eg.日期: 2020-06-08(6月8日)转换后的最终输出如下: 当天开始时间为日期: 2020-06-08T05:00:00.000Z 截

    • 问题内容: 如何使用google-api-java-client解析用户Google日历中事件的开始和结束时间? 从Google代码安装此示例android项目后,我可以进入Google日历并解析一些信息(例如所有日历,事件名称,发布时间和摘要),但是我无法终生获取事件的开始和结束时间。 我对代码的理解是这样的。 在主要活动类(CalendarAndroidSample.java)内,这是获取我每