版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/82871353
demo:
/**
* 2018年9月27日下午4:26:21
*/
package testTimeDifference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author XWF
*
*/
public class TestTimeDifference {
/**
* @param args
* @throws InterruptedException
* @throws ParseException
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) throws InterruptedException, ParseException {
String t = "12:26";
for(int i=0;i<20;i++) {
Thread.sleep(200);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date dtemp = sdf.parse(t);
Date dnow = new Date();
dtemp.setYear(dnow.getYear());
dtemp.setMonth(dnow.getMonth());
dtemp.setDate(dnow.getDate());
long msecondes = 0;
if(dtemp.getTime()<dnow.getTime()) {
Calendar c = Calendar.getInstance();
c.setTime(dtemp);
c.add(Calendar.DATE, 1);
msecondes = c.getTime().getTime()-dnow.getTime();
}else {
msecondes = dtemp.getTime()-dnow.getTime();
}
System.out.println(dnow+"与最近的"+t+"相差"+msecondes/1000/60/60%24+":"+msecondes/1000/60%60+":"+msecondes/1000%60+"."+msecondes%1000);
}
}
}
结果: