Java 以指定日期時間格式擷取目前時間、以及每隔一秒重新整理一次的方法——附帶執行個體

來源:互聯網
上載者:User

   

趁著重裝myeclipse的這會兒功夫跟大家分享一個小方法,  hope can help you guys   

  

  一、  返回目前時間字串, 咱們要用到的類有Calendar, Date, SimpleDateFormat。

      1. 先用 Calendar calendar = Calendar.getInstance();  來取得當前系統日曆的一個執行個體


      2. 用 Date date = (Date) calendar.getTime(); 取得目前時間。


      3. 用 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  來設定自己的時間格式, 順便說一下,這兒的HH是24小時制, 如果希望改成12小時制可以改成hh,
更多細節的東西可以參考API文檔, 當然也可以直接google。


      4. 用 format.format(date) 可以把date按自己指定的格式格式化, 返回一個StringBuffer。


 二、  如果需要每隔一秒重新整理一次, 還需要用到Timer, TimerTask 類。

      1. Timer timer = new Timer(); 獲得一個Timer。


      2. timer.schedule(new RemindTask(), 0, 1000);  利用timer的schedule方法指定一個任務, 每隔一秒執行一次。可以在執行任務的時候設定要重新整理的時間, 從而讓他每秒重新整理一次。這個需要在RemindTask裡設定。


      3. 在ReminTask類裡設定要更新的時間。(具體方法可參考例子)。


三、下面是一個具體的執行個體。

public class Time extends JFrame {

    JLabel label;
    JTextField text;
    String time = null;

    public Time() {
        label = new JLabel("current Time:");
        text = new JTextField();
        setBounds(300, 300, 300, 70);
        setLayout(null);
        label.setBounds(10, 10, 100, 20);
        text.setBounds(110, 10, 150, 20);
        add(label);
        add(text);
        text.setText(getTime());
        setVisible(true);

        Timer timer = new Timer();
        timer.schedule(new RemindTask(), 0, 1000);
    }

    public String getTime() {
        Calendar calendar = Calendar.getInstance();
        Date date = (Date) calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = format.format(date);

         return time;
    }

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

    private class RemindTask extends TimerTask {
         public void run() {
             text.setText(getTime());
         }
    }
}

效果  

                            ============》》》》          


當然這隻是本人用的方法, 肯定還有其他好方法, 誰有也可以分享下哦~~







相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.