如何使用jQuery/Javascript获得两个时间值? [英] How to get of two time values using jQuery/Javascript?

查看:102
本文介绍了如何使用jQuery/Javascript获得两个时间值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个值用于完成任务所需的时间.如何将这些值加在一起得出总的小时数和分钟数,但仍然有60分钟的值等于一小时?

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

我要获取的两个值的总和为HH:MM(00:00)格式.

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

谢谢!

推荐答案

这是我在周围摆的东西.它允许无限数量的参数,因此您可以使用addTime('01:00')addTime('01:00', '02:00', '03:00', '04:00')等.它具有三个功能,因为它还可以验证输入的时间是否正确格式化,如果不正确,则对它们进行格式化. (例如,确保分钟长为2位数字,如果小时长为1位数字,则用1填充零,以此类推.)

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.)

您可以在此处使用它: http://jsfiddle.net/WyxwU/

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

它也在这里:

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;
}

这篇关于如何使用jQuery/Javascript获得两个时间值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆