将我的var显示为HH:mm(javascript)

时间:2016-04-13 01:04:04

标签: javascript

我正在编写代码,这样我就可以更轻松地记录我的工作时间。我可以让分钟超过定义的时间来显示,但我似乎无法将输出上的格式设为HH:mm,这是我的代码;

<html>
<head>
<title>Time Past Since 08:30</title>
<meta http-equiv="Refresh" content="60">
<script language="JavaScript">
var sd = new Date(); // Get system date (sd)
var sh = sd.getHours(); // Get system hour (sh)
var sm = sd.getMinutes(); // Get system minutes (sm)
wh = (08); // Specify work start hour (wh)
wm =(30); // Specify work start minute (wh)
var vctime = ((sh *60 + sm) - (wh *60 + wm)); // Get differnece for system and work start, this needs to display in hh:mm but isn't
document.write(vctime); // output
</script>
</head>
<body>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

由于您的结果是几分钟,为什么不使用除法将经过的分钟数转换为小时数,然后应用模数来提取剩余的分钟数?

hours_since = Math.floor(vctime/60);
minutes_since = Math.round((vctime/60 % 1) * 60);  // Use num % 1 to extract the decimal and convert it to minutes.

console.log(hours_since + ":" + minutes_since);

如果您需要结果中的前导&#34; 0&#34; s,只需编写一个简单的条件来检查值是否小于10:

hours_zero_prefix = hours_since < 10 ? "0" : ""
minutes_zero_prefix = minutes_since < 10 ? "0" : ""
console.log(hours_zero_prefix + hours_since + ":" + minutes_zero_prefix + minutes_since);

答案 1 :(得分:0)

我建议在Moment.js库中使用diff来处理这个计算。通过计算开始和结束时间之间的差异,库将清除您可能遇到的夏令时问题。看起来你想要一个开始时间和现在之间的分钟差异。要做到这一点:

//returns number of minutes, accounting for DST based on the time zone of the local machine
var min = moment().diff(moment(yourStartDateTimeInIsoString), 'minutes');
//converts minutes to hours, then adds remaining minutes
return Math.floor(min/60) + ':' + min%60