Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - how to convert the minutes into hours and minutes with subtracted time(subtracted time values)

I want to subtract the two different 24 hours time format.

I had tried with following :

var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");

var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];

var time = th+":"+tm;

This code is working fine if second minutes is not greater than the first.but other case it will return minus values.

The above code sample values result :

time1 : 04:40
time2 : 00:55

The result should be : 03:45 (h:mi) format. But right now I am getting 04:-5 with minus value.

I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format. So how to calculate the result value and convert into hours and minutes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would try something like the following. The way I see it, it is always better to break it down to a common unit and then do simple math.

function diffHours (h1, h2) {

    /* Converts "hh:mm" format to a total in minutes */
    function toMinutes (hh) {
        hh = hh.split(':');
        return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
    }

    /* Converts total in minutes to "hh:mm" format */
    function toText (m) {
        var minutes = m % 60;
        var hours = Math.floor(m / 60);

        minutes = (minutes < 10 ? '0' : '') + minutes;
        hours = (hours < 10 ? '0' : '') + hours;

        return hours + ':' + minutes;
    }

    h1 = toMinutes(h1);
    h2 = toMinutes(h2);

    var diff = h2 - h1;

    return toText(diff);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...