Javascript月差异

时间:2010-11-30 10:45:28

标签: javascript date

如何计算Javascript中的月份差异?

请注意有类似的问题,例如: What's the best way to calculate date difference in Javascript

但这些都是基于MS的差异,有些月份的天数与其他月份不同!

计算2个日期之间的月差异的简单方法是什么?

为了清楚起见,我需要知道日期跨越多少个月,例如:

Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months

4 个答案:

答案 0 :(得分:20)

DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));

getMonth减去getMonth会给出两个月之间的月差异。

然后我们将12乘以年数差异,并将其加到结果中,给出完整的月份跨度。

答案 1 :(得分:5)

[编辑]根据评论,我有所纠正。使用接受的答案,我会使用类似的东西:

var  datefrom = new Date('2001/03/15')
    ,dateto = new Date('2011/07/21')
    ,nocando = datefrom<dateto ? null : 'datefrom > dateto!'
    ,diffM = nocando || 
             dateto.getMonth() - datefrom.getMonth() 
              + (12 * (dateto.getFullYear() - datefrom.getFullYear()))
    ,diffY = nocando || Math.floor(diffM/12)
    ,diffD = dateto.getDate()-datefrom.getDate()
    ,diffYM = nocando || 
               (diffY>0 ? ' Year(s) ' : '')
               + diffM%12+' Month(s) '+(diffD>0? (diffD+' day(s)') : '') ;

 console.log(diffYM); //=> 10 Year(s) 4 Month(s) 6 day(s)

答案 2 :(得分:3)

我在网站http://ditio.net/2010/05/02/javascript-date-difference-calculation/上找到了以下内容:

inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();

        return (d2M+12*d2Y)-(d1M+12*d1Y);
    }

在您的情况下,由于您希望在日期范围中包含所有月份,我只需通过向其添加1来修改上述代码:return (d2M+12*d2Y)-(d1M+12*d1Y) + 1;

答案 3 :(得分:1)

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 Prototypecell *cell=[tableView dequeueReusableCellWithIdentifier:@"yourIdentifier" forIndexPath:indexPath];
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [button setUserInteractionEnabled:NO];
    cell.accessoryView = button;
}