原文出处:https://blog.csdn.net/A13432421434/article/details/71346153
本篇是在原文基础上进行了修改并加以模拟。使用了Struts2框架,jQuery框架。
action类:
public String countDown() throws Exception{
Calendar startTime = Calendar.getInstance();
SimpleDateFormat simp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = simp.parse("2018-07-30 20:20:00");
startTime.setTime(date);
Calendar currentTime = Calendar.getInstance();
currentTime.setTime(new Date());
long startSecond = startTime.getTimeInMillis();
long currentSecond = currentTime.getTimeInMillis();
long totleSecond = 140 * 60;
remainingTime = (totleSecond-(currentSecond-startSecond)/1000);
return SUCCESS;
}
js:(用了jQuery框架)
$(document).ready(function(){
window.onload = function(){
var totleSecond = initTimer();
startTime(totleSecond); //开始倒计时
};
function initTimer(){
var totleSecond = Number($("#remainingTime").val()); //获取上图的input的剩余时间
return totleSecond;
}
function startTime(totleSecond){
$("#time").text(formatTime(totleSecond));
var timer = setInterval(function(){
totleSecond -= 1 ;
$("#remainingTime").val(totleSecond); //给上图的input更新剩余时间
if(totleSecond >=0 ){
$("#time").text(formatTime(totleSecond));
}else{
AutoSubmit();
alert("考试结束!");
clearInterval(timer);
$("#remainingTime").val("");
}
},1000);
}
function formatTime(totleSecond){
var hour = Math.floor(totleSecond/3600);
var minute = Math.floor((totleSecond%3600)/60);
var second = Math.floor(totleSecond%60);
hour = formatTimeNumber(hour);
minute = formatTimeNumber(minute);
second = formatTimeNumber(second);
return (hour +":"+minute+":"+second);
}
function formatTimeNumber(number){
if(number<10){
return "0"+number;
}else{
return number;
}
};
});
jsp:<input id="remainingTime" value="${remainingTime }"><span id="time"></span>
(java初学者,本博客只为记录java学习中的点点总结,非教程资料)