如何在Javascript中进行年/月计算?

时间:2012-09-24 07:34:52

标签: javascript jquery

我们有一个年/月HTML控件。基础值保留为小数。 例如:15年和2个月等于“15.02”。

我们希望根据2年/月控制(加/减)进行计算。

只是进行基本的数学计算不起作用:

  Value1 : 65.00
  Value2 : 47.09
  65.00 - 14.09 = 17.91 

 (is wrong, but should be 17.03 or (64.12 - 47.09))

是否有任何Javscript / Jquery函数或者我可以用来进行年/月计算的库?

7 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

使用小数计算的方式不起作用! coz,JS认为这个号码不是日期......

要计算年或月(基本上是任何时间/日期系统),您需要正确的语法。 Visit this用于语法

希望这对你有用

答案 2 :(得分:0)

只需将月份部分转换为常规小数(除以12),进行数学运算,然后将小数部分转换回月份(乘以12)。

你必须用var bits = Value1.split(".");之类的东西来解析这些比特。年份为bits[0]和月bits[1]

E.g。 47.09将是47 + (9 / 12 = 0.75) = 47.75

所以65 - 47.75 = 12.25

将小数部分转换回月份:0.25 * 12 = 0.3。所以答案是47.03

答案 3 :(得分:0)

在以下链接中,作者提供了有关您的要求的完整信息,请访问此链接。此链接可能对您有所帮助。 http://www.merlyn.demon.co.uk/js-date1.htm#DYMD

答案 4 :(得分:0)

JavaScript doesn’t support operator overloading,所以我认为您无法找到一个解决方案,可以让您真正使用+-复合年/月值。

但是,您可以使用加法和减法方法定义自己的年/月对象类型:

function YearsMonths(years, months) {
    this.years = years;

    if (months > 11) {
        this.years = this.years += Math.floor(months/12);
        this.months = months % 12;
    }
    else {
        if (months < 0) {
            this.months = 12 + (months % -12);
            this.years -= (Math.floor(months/-12) + 1);
        }
        else {
            this.months = months;
        }
    }
}

YearsMonths.prototype.add = function (otherYearsMonths) {
    newYears = this.years + otherYearsMonths.years;
    newMonths = this.months + otherYearsMonths.months;

    return new YearsMonths(newYears, newMonths);
}

YearsMonths.prototype.subtract = function (otherYearsMonths) {
    var newYears = this.years - otherYearsMonths.years,
        newMonths = this.months - otherYearsMonths.months;

    return new YearsMonths(newYears, newMonths);
}

然后像这样使用它:

value1 = new YearsMonths(65, 0);
value2 = new YearsMonths(47, 9);

value3 = value1.subtract(value2);
value4 = value1.add(value2);

value3.years;
# 17
value3.months;
# 3

value4.years;
# 112
value4.months;
# 9

答案 5 :(得分:0)

在这里你可以试试这个。它基本上检查您的数字是否只是几年或它们是否包含月份。该脚本只是一个模板,您可以继续并改进它,从中创建一个函数,或者定义您自己的原型。只需检查代码,希望它有所帮助。

http://jsfiddle.net/6pRGv/

答案 6 :(得分:0)

var a = '65.00'.split('.');
var b = '47.09'.split('.');
a = a[0] * 12 + Number(a[1]);
b = b[0] * 12 + Number(b[1]);
c = a - b;
c = Math.floor(c / 12) + (c % 12) / 100;