您好,登錄后才能下訂單哦!
有時候會要求實現這樣一個需求:
天、小時、分鐘、秒的數值都是隔開的,服務器端只返回一個時間戳長度。
以下就是我的實現方案,力求減少對象生成、減小計算量:
import java.util.Timer; import java.util.TimerTask; public class CountDownUtils { private static long day = 0; private static long hour = 0; private static long minute = 0; private static long second = 0; private static boolean dayNotAlready = false; private static boolean hourNotAlready = false; private static boolean minuteNotAlready = false; private static boolean secondNotAlready = false; public static void main(String[] args) { long totalSeconds = 60 * 60 * 24 * 34 + 21; initData(totalSeconds); new Timer().schedule(new TimerTask() { public void run() { if (secondNotAlready) { startCount(); } else { cancel(); } } }, 0, 1000); } /** * 初始化賦值 * * @param totalSeconds */ private static void initData(long totalSeconds) { resetData(); if (totalSeconds > 0) { secondNotAlready = true; second = totalSeconds; if (second >= 60) { minuteNotAlready = true; minute = second / 60; second = second % 60; if (minute >= 60) { hourNotAlready = true; hour = minute / 60; minute = minute % 60; if (hour > 24) { dayNotAlready = true; day = hour / 24; hour = hour % 24; } } } } System.out.println("初始格式化后——>" + day + "天" + hour + "小時" + minute + "分鐘" + second + "秒"); } private static void resetData() { day = 0; hour = 0; minute = 0; second = 0; dayNotAlready = false; hourNotAlready = false; minuteNotAlready = false; secondNotAlready = false; } /** * 計算各個值的變動 * */ public static void startCount() { if (secondNotAlready) { if (second > 0) { second--; if (second == 0 && !minuteNotAlready) { secondNotAlready = false; } } else { if (minuteNotAlready) { if (minute > 0) { minute--; second = 59; if (minute == 0 && !hourNotAlready) { minuteNotAlready = false; } } else { if (hourNotAlready) { if (hour > 0) { hour--; minute = 59; second = 59; if (hour == 0 && !dayNotAlready) { hourNotAlready = false; } } else { if (dayNotAlready) { day--; hour = 23; minute = 59; second = 59; if (day == 0) { dayNotAlready = false; } } } } } } } } System.out.println("距離截止日期還有——>" + day + "天" + hour + "小時" + minute + "分鐘" + second + "秒"); } }
總結
以上所述是小編給大家介紹的Java 實現倒計時功能(由秒計算天、小時、分鐘、秒),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。