欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-13 12:11:10
有时候会要求实现这样一个需求: 天、小时、分钟、秒的数值都是隔开的,服务器端只返回一个时间戳长度。 以下就是我的实现方案,力求减少对象生成、减小计算量:...

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

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 实现倒计时功能(由秒计算天、小时、分钟、秒),希望对大家有所帮助

上一篇:

下一篇: