趁著重裝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());
}
}
}
效果
============》》》》
當然這隻是本人用的方法, 肯定還有其他好方法, 誰有也可以分享下哦~~