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

Display my var as HH:mm (javascript)

本文关键字:mm javascript HH 我的 var 显示      更新时间:2024-06-14

我正在编写代码,这将使我能够更轻松地记录工作时间。我可以获得超过定义时间的分钟来显示,但我似乎无法将输出的格式设置为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>

既然结果是以分钟为单位的,为什么不使用除法将经过的分钟转换为小时,然后应用模数提取剩余的分钟呢?

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);

如果你需要结果中的前导"0",只需写一个简单的条件来检查值是否小于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);

我建议在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