我有三个字符串或浮点数值,例如9.30,8.00和0.40作为Total_hour,Paid_hour,Extra_hour
这些实际上应该是9小时30分钟,8小时0分钟,0小时40分钟.
问题1)如何将9.30转换为9小时30分钟
问题2)稍后想要减去并获得剩余小时= Total_hour-Paid_Hour-Extra_hour
之后答案剩余时间应该是浮动的
小智 6
以下 JavaScript 代码片段将给定的浮点数转换为小时和分钟。源浮动到时间
function convertNumToTime(number) {
// Check sign of given number
var sign = (number >= 0) ? 1 : -1;
// Set positive value of number of sign negative
number = number * sign;
// Separate the int from the decimal part
var hour = Math.floor(number);
var decpart = number - hour;
var min = 1 / 60;
// Round to nearest minute
decpart = min * Math.round(decpart / min);
var minute = Math.floor(decpart * 60) + '';
// Add padding if need
if (minute.length < 2) {
minute = '0' + minute;
}
// Add Sign in final result
sign = sign == 1 ? '' : '-';
// Return concated hours and minutes
return sign + hour + ':' + minute;
}
console.log(convertNumToTime(11.15));
Run Code Online (Sandbox Code Playgroud)
输出
11:09
Run Code Online (Sandbox Code Playgroud)
这应该工作.
你只需要转换为ms:
let timefloat = 9.3;
function convertToMs(timefloat) {
// Get the minutes portion
let remainder = timefloat % 1;
// Convert into ms
let minutes = remainder * 100 * 60 * 1000;
// Get the number of hours and convert to ms
let hours = (timefloat - remainder) * 60 * 60 * 1000;
return minutes + hours;
}
// Convert back to float format
function convertToFloat(date) {
let hours = date.getUTCHours();
let mins = date.getUTCMinutes();
return hours + (mins / 100);
}
// Log the result
console.log(new Date(convertToMs(9.3)).toUTCString());
console.log(new Date(convertToMs(8.0)).toUTCString());
console.log(new Date(convertToMs(9.3) - convertToMs(8.0)).toUTCString());
let diff = convertToMs(9.3) - convertToMs(8.0);
console.log(convertToFloat(new Date(diff)))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2411 次 |
| 最近记录: |