我正在将javascript中两个日期之间的差异转换为Days:Hours:Mins格式。
<html>
<head>
<script type="text/javascript"
src="jquery-1.9.1.min.js""></script>
<script type="text/javascript">
$(document).ready(function(){
var today = new Date();
var before = new Date();
before.setDate(today.getDate() - 3);
var diff = today.getTime() - before.getTime();
var diffMinutes = diff / (60 * 1000) % 60;
var diffHours = diff / (60 * 60 * 1000) % 24;
var diffDays = diff / (24 * 60 * 60 * 1000);
$('#days')[0].innerHTML = diffDays;
$('#hours')[0].innerHTML = diffHours;
$('#minutes')[0].innerHTML = diffMinutes;
setInterval(myfunc,60000);
function myfunc(){
if(diff > 0){
diff = diff - 60000;
diffMinutes = diff / (60 * 1000) % 60;
diffHours = diff / (60 * 60 * 1000) % 24;
diffDays = diff / (24 * 60 * 60 * 1000);
$('#days')[0].innerHTML = Math.floor(diffDays);
$('#hours')[0].innerHTML = Math.floor(diffHours);
$('#minutes')[0].innerHTML = diffMinutes;
}
}
});
</script>
</head>
<body>
<div>
<table>
<tr>
<td>
<label>Days:</label>
</td>
<td>
<label id="days"></label>
</td>
<td>
<label>Hours:</label>
</td>
<td>
<label id="hours"></label>
</td>
<td>
<label>Mintues:</label>
</td>
<td>
<label id="minutes"></label>
</td>
</tr>
</table>
</div>
</body>
当计算差异时,它将像天:2小时:4分钟:52
我想要的是,如果天或小时是一位数,我想在它们之前追加0。
如何做到这一点?是否可以使用正则表达式或数字格式?