【问题标题】:Calculate month with days in javascript在javascript中用天数计算月份
【发布时间】:2013-09-17 20:55:58
【问题描述】:

我想用javascript计算月份。

我的要求是我的日期范围在 24 个月内。

我有 todate 来自 2012 年 9 月 24 日的某个地方

现在,

如果我在 from date 中输入 2010 年 8 月 31 日,在 todate 中输入 2012 年 9 月 24 日,则会显示错误消息。

目前我正在这样做

todate.getMonth() - fromdate.getMonth() + (12 * (todate.getFullYear() - fromdate.getFullYear()))

但是, 如果我从日期和 2012 年 9 月 24 日输入 2010 年 9 月 23 日,它也应该显示错误消息..

但是,它允许我那个日期..比日期晚 24 个月..所以,我如何计算不允许我上面给定日期的日期的月份。

谢谢

【问题讨论】:

  • 你能不能不要用数字代替像to这样的词?这非常令人困惑。 因为我有 2 显示 2 年/24 个月的数据 是什么意思?
  • @mplungjan..hey,谢谢您的建议...我的要求是我的日期范围将在 24 个月内
  • months = moment(from).diff(moment(to), "months")
  • @thg456 什么是时刻??

标签: javascript validation date javascript-framework extjs4.2


【解决方案1】:

您的问题是,如果相隔两年是同一个月份,您还需要检查月份中的哪一天。

function isValidDate (from, to) {
  var months = to.getMonth() - from.getMonth() + 
              (12 * (to.getFullYear() - from.getFullYear()));
  return months < 24 || months === 24 && to.getDate() < from.getDate();
}

【讨论】:

    【解决方案2】:

    试试这个来获得天数


    function finddays(date_from, date_to) 
    {return Math.round(Math.abs(new Date(date_from).getTime() - new Date(date_to).getTime())/(1000 * 60 * 60 * 24))}
    

    使用:

    finddays("2010 年 9 月 23 日", "2010 年 9 月 25 日");

    更新

    不推荐,但效果更好
    试试这个以获得几个月(希望一个月 30 天,容易出错 +-3/年)


     function findMonths(date_from, date_to) 
        {return Math.round((new Date(date_to).getTime()-new Date(date_from).getTime())/(1000 * 60 * 60 * 24*30))}
    

    使用:

    findMonths("2010 年 9 月 23 日", "2010 年 10 月 25 日");

    【讨论】:

    • 但他正在寻找 findmonths,而不是 finddays
    猜你喜欢
    • 2019-01-03
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2020-05-09
    相关资源
    最近更新 更多