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

前端 未结 4 1288
感情败类
感情败类 2020-12-22 01:41

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         


        
相关标签:
4条回答
  • 2020-12-22 01:49

    Try:

    var time1 = Date.UTC(0,0,0,4,40,0);
    var time2 = Date.UTC(0,0,0,0,55,0);
    
    var subtractedValue = time1 - time2;
    
    var timeResult = new Date(subtractedValue);
    
    console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
    

    DEMO

    This solution utilizes javascript built-in date. How it works:

    var time1 = Date.UTC(0,0,0,4,40,0);
    var time2 = Date.UTC(0,0,0,0,55,0);
    

    time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.

    var subtractedValue = time1 - time2;
    

    subtractedValue is the difference in miliseconds.

    var timeResult = new Date(subtractedValue);
    
    console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
    

    These lines reconstruct a date object to get hours and minutes.

    0 讨论(0)
  • 2020-12-22 01:51

    This works better , A fiddle I just found

    var difference = Math.abs(toSeconds(a) - toSeconds(b));
    

    fiddle

    0 讨论(0)
  • 2020-12-22 01:57

    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);
    }
    
    0 讨论(0)
  • 2020-12-22 02:02

    This method may work for you:

    function timeDiff(s,e){
        var startTime = new Date("1/1/1900 " + s);
        var endTime = new Date("1/1/1900 " + e);
        var diff = startTime - endTime;
        var result = new Date(diff);
        var h = result.getUTCHours();
        var m = result.getUTCMinutes();    
        return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
    }
    
    var startingTimeValue = "04:40";
    var endTimeValue = "00:55";
    var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
    

    Demo: http://jsfiddle.net/zRVSg/

    0 讨论(0)
提交回复
热议问题