Java display current time

前端 未结 6 1931
一向
一向 2021-01-02 02:05

I have a code which shows me the current date and time when I run my application

DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");
Calen         


        
6条回答
  •  自闭症患者
    2021-01-02 02:55

    You can try this,

    import java.awt.*;
    import java.awt.event.*;
    import java.util.Date;
    import java.lang.Thread;
    
    public class TimeInSeconds extends Frame implements Runnable
    {
        private Label lblOne;
        private Date dd;
        private Thread th;
    
        public TimeInSeconds()
        {
            setTitle("Current time");
            setSize(200,150);
            setVisible(true);
            setLayout(new FlowLayout());
            addWindowListener(new WindowAdapter() {
                public void windowClose(WindowEvent we){
                    System.exit(0);
                }
            });
            lblOne = new Label("00:00:00");
            add(lblOne);
    
            th = new Thread(this);
            th.start(); // here thread starts
        }
    
        public void run()
        {
            try
            {
                do
                {
                    dd = new Date();
                    lblOne.setText(dd.getHours() + " : " + dd.getMinutes() + " : " + dd.getSeconds());
                    Thread.sleep(1000);  // 1000 = 1 second
                }while(th.isAlive());
            }
            catch(Exception e)
            {
    
            }
        }
    
        public static void main(String[] args)
        {
            new TimeInSeconds();
        }
    }
    

    You can run this program and get the output.

    For more info on date and time in java you can refer links below,

    https://docs.oracle.com/javase/tutorial/datetime/iso/datetime.html

    https://docs.oracle.com/javase/7/docs/api/java/sql/Date.html

    http://www.flowerbrackets.com/date-time-java-program/

提交回复
热议问题