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

   

趁着重装myeclipse的这会儿功夫跟大家分享一个小方法,  hope can help you guys  微笑 

  

  一、  返回当前时间字符串, 要用到的类有CalendarDateSimpleDateFormat

      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。


 二、  如果需要每隔一秒刷新一次, 还需要用到TimerTimerTask 类。

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

}


效果如图:  

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









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值