How to get of two time values using jQueryJavascript? - Stack Overflow

I have two values that are used for the amount of time it will take to plete a task. How can I add thes

I have two values that are used for the amount of time it will take to plete a task. How can I add these values together to e up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?

The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.

Thanks!

I have two values that are used for the amount of time it will take to plete a task. How can I add these values together to e up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?

The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.

Thanks!

Share Improve this question edited Mar 12, 2011 at 20:45 Ateş Göral 140k27 gold badges141 silver badges191 bronze badges asked Mar 12, 2011 at 20:10 hsatterwhitehsatterwhite 7,3555 gold badges27 silver badges29 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

Writing your own time and date functions can get plex. Why re-invent the wheel. Take a look at the excellent http://www.datejs./ date library. It handles all date and time related tasks and usage is very simple.

Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)

You can play with it here: http://jsfiddle/WyxwU/

It's also here:

var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);

function addTime()
{
    if (arguments.length < 2)
    {
        if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
        else return false;
    }

    var time1Split, time2Split, totalHours, totalMinutes;
    if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
    else return false;

    for (var i = 1; i < arguments.length; i++)
    {
        // Add them up
        time1Split = totalTime.split(':');
        time2Split = arguments[i].split(':');

        totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
        totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);

        // If total minutes is more than 59, then convert to hours and minutes
        if (totalMinutes > 59)
        {
            totalHours += Math.floor(totalMinutes / 60);
            totalMinutes = totalMinutes % 60;
        }

        totalTime = totalHours + ':' + padWithZeros(totalMinutes);
    }

    return totalTime;
}

function isFormattedDate(date)
{
    var splitDate = date.split(':');
    if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
    else return false;
}

function padWithZeros(number)
{
    var lengthOfNumber = (parseInt(number) + '').length;
    if (lengthOfNumber == 2) return number;
    else if (lengthOfNumber == 1) return '0' + number;
    else if (lengthOfNumber == 0) return '00';
    else return false;
}

Here is the simple JS code for this,


var a = "2:50";
var b = "2:15";

var splitTimeStr = function(t){
        var t = t.split(":");
        t[0] = Number(t[0]);
            t[1] = Number(t[1]);
        return t;
};

var addTime = function(t1, t2){
    var t1Hr = splitTimeStr(t1)[0];
    var t1Min = splitTimeStr(t1)[1];
    var t2Hr = splitTimeStr(t2)[0];
    var t2Min = splitTimeStr(t2)[1];
    var rHr = t1Hr + t2Hr;
    var rMin = t1Min + t2Min;
    if (rMin >= 60)
    {
        rMin = rMin - 60;
        rHr = rHr + 1;
    }
    if (rMin < 10) rMin = "0" + rMin;
    if (rHr < 10) rHr = "0" + rHr;
    return "" + rHr + ":" + rMin;
};

document.write(addTime(a, b));

you can validate/play this with code here: http://jsfiddle/z24v7/

What you have to do is calculate them to a decimal by that I mean. Strip out the hour/mins multiple that by 60 + to mins

//strip out the hours l_hour = Number(l_time$.substr(0, l_pos)); //Strip out the mins l_min = Number(l_time$.substr(l_pos + 1, l_time$.length)); //add the two values divided by 60 mins l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);

Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time l_difference_in_min = l_difference * 60; l_time_mins = l_difference_in_min%60; l_time_hours = (l_difference_in_min - l_mins)/60;

Now just format the two to be HH:MM

I would break the problem into sub-tasks that are reusable. You have to concerns here:

  1. Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
  2. Format a given number of minutes into a time string in "hh:mm" format.

The fact that you're adding two times together is a diversion from the actual two problems above.

  1. Parse a time string into minutes:

    function parseMinutes(s) {
        var tokens = s.split(":");
        return tokens[0] * 60 + parseInt(tokens[1]);
    }
    
  2. Format minutes into a time string:

    function formatMinutes(minutes) {
        function pad(n) {
            return n > 9
                ? n
                : ("0" + n);
        }
    
        var hours = Math.floor(minutes / 60),
            mins = minutes % 60;
        return pad(hours) + ":" + pad(mins);
    }
    

Then your specific problem can be tackled by:

var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742287883a4415651.html

相关推荐

  • How to get of two time values using jQueryJavascript? - Stack Overflow

    I have two values that are used for the amount of time it will take to plete a task. How can I add thes

    19小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信