有時(shí)候會(huì)要求實(shí)現(xiàn)這樣一個(gè)需求:
成都創(chuàng)新互聯(lián)公司主要從事成都網(wǎng)站建設(shè)、成都網(wǎng)站制作、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)雙鴨山,十載網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):18982081108
天、小時(shí)、分鐘、秒的數(shù)值都是隔開的,服務(wù)器端只返回一個(gè)時(shí)間戳長(zhǎng)度。
以下就是我的實(shí)現(xiàn)方案,力求減少對(duì)象生成、減小計(jì)算量:
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 + "小時(shí)" + minute + "分鐘" + second + "秒"); } private static void resetData() { day = 0; hour = 0; minute = 0; second = 0; dayNotAlready = false; hourNotAlready = false; minuteNotAlready = false; secondNotAlready = false; } /** * 計(jì)算各個(gè)值的變動(dòng) * */ 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 + "小時(shí)" + minute + "分鐘" + second + "秒"); } }
總結(jié)
以上所述是小編給大家介紹的Java 實(shí)現(xiàn)倒計(jì)時(shí)功能(由秒計(jì)算天、小時(shí)、分鐘、秒),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)創(chuàng)新互聯(lián)網(wǎng)站的支持!