您好,登錄后才能下訂單哦!
這篇文章主要講解了“Java怎么實現倒計時時分秒”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Java怎么實現倒計時時分秒”吧!
package com.test; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Timer; import java.util.TimerTask; /** * 多任務定時器 * * */ public class Testsss { public final static Map<String,String> map = new HashMap<>(); public static void main(String[] args) { String nowdate = "2019-09-09 10:28:17"; String startdate = "2019-09-09 10:28:20"; Date nowdate1 = parseToDateTime(nowdate,"yyyy-MM-dd HH:mm:ss"); Date startdate1 = parseToDateTime(startdate,"yyyy-MM-dd HH:mm:ss"); String nowdate2 = "2019-09-09 10:20:17"; String startdate2 = "2019-09-09 10:20:21"; Date nowdate12 = parseToDateTime(nowdate2,"yyyy-MM-dd HH:mm:ss"); Date startdate12 = parseToDateTime(startdate2,"yyyy-MM-dd HH:mm:ss"); int deff = getBetweenTimes(nowdate1,startdate1); System.out.println(deff); int deff2 = getBetweenTimes(nowdate12,startdate12); System.out.println(deff2); map.put("id1", String.valueOf(deff)); map.put("id2", String.valueOf(deff2)); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("timer ...."); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); String taskId = (String)entry.getKey(); String time = (String)entry.getValue(); int times = Integer.parseInt(time); if(times>=0) { times--; map.put(taskId,String.valueOf(times)); System.out.println(taskId+"->"+framt(Integer.parseInt(time))); }else { map.remove(taskId); } if(map.size()==0) { System.out.println("done"); timer.cancel(); } } } },0,1000); } /** * 秒轉時分秒 * * @param seconds */ public static String framt(int seconds) { int temp=0; StringBuffer sb=new StringBuffer(); temp = seconds/3600; sb.append((temp<10)?"0"+temp+":":""+temp+":"); temp=seconds%3600/60; sb.append((temp<10)?"0"+temp+":":""+temp+":"); temp=seconds%3600%60; sb.append((temp<10)?"0"+temp:""+temp); return sb.toString(); } /** * 將字符串轉換為指定格式的日期時間 * * @param strDate * 日期字符串 * @param pattern * 日期格式,與strDate格式匹配 */ public static Date parseToDateTime(String strDate, String pattern) { try { return new SimpleDateFormat(pattern).parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 時間差 秒 * */ public static int getBetweenTimes(Date start, Date end) { long times = end.getTime() - start.getTime(); return (int) times / 1000; } }
感謝各位的閱讀,以上就是“Java怎么實現倒計時時分秒”的內容了,經過本文的學習后,相信大家對Java怎么實現倒計時時分秒這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。