说明: 碰到一个需求,从后端返回一个字符串"01:02",这代表1小时2分钟,需要根据返回的字段在前端展示一个倒计时的功能,用java写了一个,利用线程和时间换算实现。
steo1: java
package com.example.demo2;
import com.example.demo2.entity.*;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.boot.test.context.SpringBootTest;
import java.text.*;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Date;
@SpringBootTest(classes = {Demo2Application.class}, properties = {"application.properties"})
public class Test {
@org.junit.Test
public void test() throws ParseException {
int hour = 1; //设置倒计时的 时和分
int minute = 2;
long c2 = minute * 60 * 1000 + hour * 60 * 60 * 1000;
System.out.println(c2);
String a = formatTime(c2);
System.out.println(a);/*可以 反正这个是一个简单的倒计时 网上肯定有代码的*/
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
c2 = c2 - 1000;
System.out.println(formatTime(c2));
}
}
public static String formatTime(Long ms) {
Integer ss = 1000;
Integer mi = ss * 60;
Integer hh = mi * 60;
Integer dd = hh * 24;
Long day = ms / dd;
Long hour = (ms - day * dd) / hh;
Long minute = (ms - day * dd - hour * hh) / mi;
Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
StringBuffer sb = new StringBuffer();
if (day > 0) {
sb.append(String.format("%02d",day) + "天");
}
if (hour >= 0) {
sb.append(String.format("%02d",hour) + ":");
}
if (minute >= 0) {
sb.append(String.format("%02d",minute) + ":");
}
if (second >= 0) {
sb.append(String.format("%02d",second));
}
if (milliSecond > 0) {
sb.append(milliSecond + "毫秒");
}
return sb.toString();
}
}
step2: run
00:01:00
00:00:59
00:00:58
00:00:57
00:00:56
00:00:55