这篇文章主要讲解了“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怎么实现倒计时时分秒这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/Thinkeryjgfn/blog/3103817