Advertisement

java距离指定时间还有多少天

阅读量:
复制代码
    		private static final long serialVersionUID = 1L;
         private static int DELAY = 0;
         private static int PERIOD = 1000;
         //指定时间(可以任意修改)
         private static final String DATE_TIME = "2021年11月30日";
         private static final String INFO = "距 " + DATE_TIME + " 有: ";
         private long that;
         private JLabel label;
    
        public Tester (){
            setTitle ("倒计时牌");
            setResizable (false);
            setLayout (new BorderLayout ());
            setSize (200, 100);
            setLocationRelativeTo (null);
            setAlwaysOnTop (true);
            setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        }
    
        private Tester runTimer ()
        {
            Timer timer = new Timer ();
            timer.schedule (new TimerTask () {
                @Override
                public void run() {
                    long ms = that - new Date().getTime ();
                    int day = (int) ( ms / 1000 / 60 / 60 / 24 );
                    int hour = (int) ( ms  / 1000 / 60 / 60 % 24 );
                    int minute = (int) ( ms / 1000 / 60 % 60 );
                    int second = (int) ( ms / 1000 % 60 );
                    label.setText ("<html>" + INFO + "<font color='red'>"
                            + day + " 天 " + hour + " 时 " + minute + " 分 " + second + " 秒." + "</font></html>");
                }
                },DELAY,PERIOD);
            return this;
        }
    
        private Tester init(){
            String format = "";
            if (DATE_TIME.matches ("^\ d+年$")){
               format = "yyyy年";
            }else if (DATE_TIME.matches ("\ d+年\ d+月")){
               format = "yyyy年MM月";
            }else if (DATE_TIME.matches ("\ d+年\ d+月\ d+日")){
               format = "yyyy年MM月dd日";
            }
            SimpleDateFormat sdf = new SimpleDateFormat (format);
            try{
             that = sdf.parse (DATE_TIME).getTime();
            }catch (ParseException e){
             e.printStackTrace();
            }
            label = new JLabel();
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
            panel.add(label);
            add(panel,BorderLayout.CENTER);
            return this;
        }
    
        public static void main ( String[] args){
            SwingUtilities.invokeLater (new Runnable(){
                @Override
                public void run(){
                    new Tester().init().runTimer().setVisible(true);
                }
            });	
        }

全部评论 (0)

还没有任何评论哟~