我想计算两次之间的差异。
时间格式为Intime="00:05:53"
和Outtime="00:17:31"
我已尝试过以下代码,但我得到的结果如totalhours="00:-12:22".
而不是totalhours="00:11:38"
。我究竟做错了什么?我该怎么办呢?
var inhh=0;
var inmm=0;
var inss=0;
var outhh=0;
var outmm=0;
var outss=0;
var inTime = document.getElementById("intime").value;
var outTime = document.getElementById("outtime").value;
var intimeAarry=inTime.split(":");
inhh= parseInt(intimeAarry[0]);
inmm=parseInt(intimeAarry[1]);
inss=parseInt(intimeAarry[2]);
if (inss > 60) {
inmm = inmm + 1;
inss = inss % 60;
}
if (inmm > 60) {
inhh = inhh + 1;
inmm = inmm % 60;
}
var hh;
var mm;
var ss;
var outtimeArray=outTime.split(":");
outhh= parseInt(outtimeArray[0]);
outmm=parseInt(outtimeArray[1]);
outss=parseInt(outtimeArray[2]);
if (outss > 60) {
outmm = outmm + 1;
outss = outss % 60;
}
if (outmm > 60) {
outhh = outhh + 1;
outmm = outmm % 60;
}
hh=outhh-inhh;
mm=outmm-inmm;
ss=outss-inss;
var hhh = hh == 0 ? "0" + hh : hh;
var mmm = mm == 0 ? "0" + mm : mm;
var sss = ss == 0 ? "0" + ss : ss;
var totalhours = hhh + ":" + mmm + ":" + sss;
答案 0 :(得分:1)
查看http://momentjs.com/了解所有日期和时间需求。
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
(function(){
var Intime = moment("00:05:53", "HH:mm:ss");
var Outtime = moment("00:17:31", "HH:mm:ss");
console.log( Outtime.diff( Intime, "minutes") );
})()
</script>
答案 1 :(得分:1)
尝试这会有所帮助
var diff = ( new Date("1970-1-1 " + Outtime) - new Date("1970-1-1 " + Intime) ) / 1000 / 60 / 60;
答案 2 :(得分:0)
您的代码失败的原因是您不能简单地相互减去这些部分。一个简单的策略是将它们转换为公共单位,进行减法,然后转换回合适的格式。
您的代码看起来过于复杂,请考虑以下内容。它通过首先将它们转换为秒,获得差异,然后转换回hh:mm:ss格式的时间来获得两次之间的差异:
// Return seconds given a time in h:m:s format
function timeToSecs(t) {
var b = t.split(':');
return b[0]*3.6e3 + b[1]*60 + +b[2];
}
// Return hh:mm:ss given seconds
function secsToTime(s) {
function z(n){return (n<10? '0' : '') + n}
var sign = s < 0? '-' : '';
s = Math.abs(s);
return sign + z(s/3.6e3|0) + ':' + z(s%3.6e3/60|0) + ':' + z(s%60);
}
// Return the difference between two times in h:m:s format
function (t0, t1) {
return secsToTime(timeToSecs(t1) - timeToSecs(t0));
}
console.log(getTimeDiff('00:05:53', '00:17:31')); // 00:11:38
console.log(getTimeDiff('00:17:31', '00:05:53')); // -00:11:38
console.log(getTimeDiff('08:57:01', '17:23:41')); // 08:26:40
答案 3 :(得分:0)
您可以通过以下代码实现您的工作方式
var Intime="01:55:02";
var Outtime="05:23:01";
var IntA=Intime.split(":");
var inhh=parseInt(IntA[0])
var inmm=parseInt(IntA[1])
var inss=parseInt(IntA[2])
var outA=Outtime.split(":");
var ouhh=parseInt(outA[0])
var oumm=parseInt(outA[1])
var ouss=parseInt(outA[2])
if(ouhh>inhh)
{
if((ouss-inss)<0)
{
oumm=oumm-1;
rss=60+ouss-inss;
}
else
{
rss=ouss-inss;
}
if((oumm-inmm)<0)
{
ouhh=ouhh-1;
rmm=60+oumm-inmm;
}
else
{
rmm=oumm-inmm;
}
rhh=ouhh-inhh;
var diff=rhh+":"+rmm+":"+rss
console.log(diff)//is the required difference
}
这个小提琴是here