Java倒计时实例

时间:2022-06-08 22:02:29
public class CountDownDemo {
	
	public static void main(String[] args) {
		while( true ){
			try {
				Thread.sleep(1000);
				DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date myDate = dateFormat.parse("2016-4-22 12:00:00");
				long targetTimeMillis = myDate.getTime();
				long currentTimeMillis = System.currentTimeMillis();
				long gapSecondTime = (targetTimeMillis - currentTimeMillis)/1000;
				int d = (int) gapSecondTime/(24*60*60); // 换算成小时数
				int h = (int)(gapSecondTime/(60*60)%24); //换算成分钟数,以24小时切分,多出的部分就是要显示的分钟数
				int m = (int)(gapSecondTime/(60)%60);//换算成分钟
				int s = (int)(gapSecondTime%60);//本身gapSecondTime就是秒数,mod 60 获得的就是剩余描述
				System.out.println("剩余时间:"+d+"天"+h+"小时"+m+"分钟"+s+"秒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
}