倒计时 日时分秒 java_Java倒计时时分秒-多时间

本文介绍了一个基于Java的多任务定时器实现案例,通过使用Timer类安排周期性任务,并利用HashMap来跟踪不同任务的状态。该定时器能够计算两个指定时间点之间的差值并定时更新状态。

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 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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值