欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java 实现倒计时功能(由秒计算天、小时、分钟、秒)

时间:2020-11-15 13:41:39|栏目:JAVA代码|点击:

有时候会要求实现这样一个需求:

天、小时、分钟、秒的数值都是隔开的,服务器端只返回一个时间戳长度。

以下就是我的实现方案,力求减少对象生成、减小计算量:

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生成二维码工具类示例代码

栏    目:JAVA代码

下一篇:java selenium教程环境搭建方法

本文标题:Java 实现倒计时功能(由秒计算天、小时、分钟、秒)

本文地址:http://www.codeinn.net/misctech/22667.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有