您的位置:首页 > 编程语言 > Java开发

Java 以指定日期时间格式获取当前时间、以及每隔一秒刷新一次的方法------附带实例

2012-02-05 11:08 1701 查看
趁着重装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());

}

}

}

效果如图:



============》》》》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: