如何在 JavaScript 中将时间转换为十进制数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10893613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert time to decimal number in JavaScript?
提问by idleberg
I'm too lazy to fill out my time sheet at work by the end at the end of every month, so I've started adding some functions to our PDF form. Acrobat Pro offers to make advanced calculations using JavaScript, but I'm stuck with this problem.
我懒得在每个月底的时候填写我的工作时间表,所以我开始在我们的 PDF 表单中添加一些功能。Acrobat Pro 提供使用 JavaScript 进行高级计算,但我被这个问题困住了。
I have two fields in which I enter the time when I start/end working. I want to calculate my overtime and output the result in a third field. however, I want the output to be decimal, so when I make half an hour overtime, the result would be 0.5
我有两个字段,可以在其中输入开始/结束工作的时间。我想计算我的加班时间并将结果输出到第三个字段中。但是,我希望输出是十进制的,所以当我加班半小时时,结果将是 0.5
Example: my work time is 8.5 hours, I start a 7.30 and finish at 16.00 (4 pm).
示例:我的工作时间是 8.5 小时,我从 7.30 开始并在 16.00(下午 4 点)结束。
My code so far:
到目前为止我的代码:
var workTime = this.getField ("Work time").value;
var startTime = this.getField ("Start time").value;
var endTime = this.getField ("End time").value;
event.value = workTime - (endTime - startTime);
回答by Amadan
Separate hours and minutes, divide minutes by 60
, add to hours.
将小时和分钟分开,将分钟除以60
,再加上小时。
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hours = parseInt(hoursMinutes[0], 10);
var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hours + minutes / 60;
}
回答by Meloman
In my case I use it for calculating time on invoice.
就我而言,我用它来计算发票上的时间。
The input could contain these 6 ways to write it for the user :
输入可以包含以下 6 种为用户编写的方式:
- 1 -> 1 hour 0 minutes
- 1,2 -> 1 hour 12 minutes
- 1.5 -> 1 hour 30 minutes
- 1:30 -> 1 hour 30 minutes
- 1h40 -> 1 hour 40 minutes
- 45m -> 0 hour 45 minutes
- 1 -> 1 小时 0 分钟
- 1,2 -> 1 小时 12 分钟
- 1.5 -> 1 小时 30 分钟
- 1:30 -> 1 小时 30 分钟
- 1h40 -> 1 小时 40 分钟
- 45m -> 0 小时 45 分钟
So I used this (thanks to Amadan), here is working code :
所以我使用了这个(感谢 Amadan),这是工作代码:
function time2dec(tIn) {
if(tIn == '')
return 0;
if(tIn.indexOf('h') >= 0 || tIn.indexOf(':') >= 0)
return hm2dec(tIn.split(/[h:]/));
if(tIn.indexOf('m') >= 0)
return hm2dec([0,tIn.replace('m','')]);
if(tIn.indexOf(',') >= 0)
return parseFloat(tIn.split(',').join('.')).toFixed(2);
if(tIn.indexOf('.') >= 0)
return parseFloat(tIn);
return parseInt(tIn, 10);
}
function hm2dec(hoursMinutes) {
var hours = parseInt(hoursMinutes[0], 10);
var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return (hours + minutes / 60).toFixed(2);
}
Example of use (with jQuery) :
使用示例(使用 jQuery):
var qty = time2dec($('#qty').val());
var price = parseFloat($('#price').val());
var total = (qty * price).toFixed(2);
Hope it could help some of us.
希望它可以帮助我们中的一些人。
回答by Svetoslav
Another way ;)
其它的办法 ;)
var aHours = 4.45;
var aHoursInMinutes = (Math.floor(aHours) * 60 )+ ((aHours - Math.floor(aHours)) * 100);
// 285 minutes;
var afromMinutesToHours =
(Math.floor(aHoursInMinutes /60) + ((aHoursInMinutes - (60* Math.floor(aHoursInMinutes /60)))/100));
// 4.45 hours;
var bHours = 0.33;
var bHoursInMinutes = (Math.floor(bHours) * 60 )+ ((bHours - Math.floor(bHours)) * 100); // 33 minutes;
var bFromMinutesToHours =
(Math.floor(bHoursInMinutes / 60) + (( bHoursInMinutes - (60 * Math.floor(bHoursInMinutes / 60)))/100)); // 0.33 hours;
var resultInMinutes = aHoursInMinutes + bHoursInMinutes;
var resultToHours =
(Math.floor(resultInMinutes / 60) + (( resultInMinutes - (60 * Math.floor(resultInMinutes / 60)))/100)); // 5.18 hours;
回答by Roberto
As alternative, I was curious if this could be done using Date.parse
, and it can.
作为替代方案,我很好奇这是否可以使用 来完成Date.parse
,并且可以。
The following code returns the same values as the selected answer, except for garbage input in which case it returns zero. The 1970 date is used because that is UNIX time zero.
以下代码返回与所选答案相同的值,除了垃圾输入在这种情况下返回零。使用 1970 日期是因为这是 UNIX 时间零。
Note that MDN says, "It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent."
请注意,MDN 说,“不建议使用 Date.parse,因为直到 ES5,字符串的解析完全依赖于实现。”
var test = [undefined, null, "", "garbage", "0", "00:00", " 01:11", "3:44", "2:3", "5.06"];
var hours = 0;
var html = "<table>";
for (var i = 0; i < test.length; i++) {
html += "<tr>";
html += "<td>" + test[i] + "</td>";
hours = timeStringToFloat(test[i]);
html += "<td>" + hours + "</td>";
hours = timeStringToNumber(test[i]);
html += "<td>" + hours + "</td>";
html += "<td>" + hoursToString(hours) + "</td>";
html += "</tr>";
}
stdout.innerHTML = html;
function timeStringToNumber(time) {
return ((new Date(("01 Jan 1970 " + time || "").replace(".", ":") + " GMT")) / 3600000) || 0;
}
function timeStringToFloat(time) {
try {
var hoursMinutes = time.split(/[.:]/);
var hours = parseInt(hoursMinutes[0], 10);
var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hours + minutes / 60;
} catch (e) {
return "ERROR";
}
}
function hoursToString(hours) {
var minutes = hours * 60;
return (
("00" + Math.floor(minutes / 60)).slice(-2) +
":" +
("00" + Math.round(minutes % 60)).slice(-2)
);
}
body {
font-family: sans-serif;
font-size: 12px;
}
h4 {
color: white;
background-color: steelblue;
padding: 0.5em;
}
table {
border-collapse: collapse;
}
table td {
border: 1px solid gray;
min-height: 1em;
}
<h4>Test Output:</h4>
Method A is the original and Method B the alternative.
<table>
<thead>
<tr>
<th>String</th>
<th>Method A</th>
<th>Method B</th>
<th>ToString</th>
</tr>
</thead>
<tbody id="stdout"></tbody>
</table>
*
*
function timeStringToNumber( time )
{
return ((new Date(("01 Jan 1970 " + time || "").replace(".",":") + " GMT")) / 3600000) || 0;
}