javascript 如何获得两个日期之间的月份

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19290421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:01:13  来源:igfitidea点击:

How to get the months between 2 dates

javascriptjqueryjquery-uidatedatepicker

提问by Slim

I'm using jquery datepickerin order to get 2 dates. In my case I have to get the date in this format d-M-y. I'm using it in order to be able to insert the values into an oracledatabase without any formating. The problem is that I need to calculate the months between 2 dates. For example: 1-Oct-13- 30-Oct-16.

我正在使用 jquerydatepicker来获取 2 个日期。就我而言,我必须以这种格式获取日期d-M-y。我使用它是为了能够在oracle不进行任何格式化的情况下将值插入到数据库中。问题是我需要计算两个日期之间的月份。例如:1-Oct-13- 30-Oct-16

Here is how I'm getting the dates in my js:

这是我如何在我的 js 中获取日期:

LastAssimDatePicker = (function() {
                        $( "#lastAssimilationDate" ).datepicker({
                            yearRange: "-20:+100",
                            changeMonth: true,
                            changeYear: true,
                            dateFormat: "d-M-y"
                        });
                    }),

LastAssimDateOverPicker = (function() {
                        $( "#lastAssimilationDateOver" ).datepicker({
                            yearRange: "-20:+100",
                            changeMonth: true,
                            changeYear: true,
                            dateFormat: "d-M-y"
                        });
                    }),

The above dates are assigned to 2 variables- lastAssimilationDateand LastAssimDateOver

上述日期分配给2 variables-lastAssimilationDateLastAssimDateOver

The problem is that I really can't find a way to calculate the months between the 2 dates and I already lost about 2 hours on it. I'm pretty sure that there will be an easy solution, but as a beginner, I'm not able to spot it. I know that there are simmilar topics here, but I can't get it working, or it does not fit on my issue.

问题是我真的找不到计算两个日期之间的月份的方法,而且我已经浪费了大约 2 个小时。我很确定会有一个简单的解决方案,但作为初学者,我无法发现它。我知道这里有类似的主题,但我无法让它工作,或者它不适合我的问题。

回答by Tats_innit

Working Demohttp://jsfiddle.net/w54pq/orin case you want both month included try this demo: http://jsfiddle.net/yQyJq/

工作演示http://jsfiddle.net/w54pq/或者如果你想要两个月都包括试试这个演示:http: //jsfiddle.net/yQyJq/

This will fit your need, there can be many version for it.

这将满足您的需要,它可以有很多版本。

Please note there can be various combinations with your need so feel free to play around with this code.

请注意,您可以根据需要进行各种组合,因此请随意使用此代码。

Old link one of which is my old reply:

旧链接其中之一是我的旧回复:

Hope this helps :)

希望这可以帮助 :)

code

代码

$('.start,.end').datepicker();

$('.hulk').click(function () {
    var sDate = $('.start').val();
    var nDate = $('.end').val();

    var startdate = new Date(sDate);
    var enddate = new Date(nDate);

    enddate.setDate(enddate.getDate() - startdate.getDate());
    alert(monthDiff(startdate,enddate));
});


function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

Working shot

工作镜头

enter image description here

在此处输入图片说明

回答by Praveen

Since you mentioned that you are not supposed to change the format I have a solution for you.

由于您提到您不应该更改格式,因此我为您提供了解决方案。

With the help of @T.J. Crowder's Answer, I done this

在@TJ Crowder's Answer的帮助下,我做到了

d1 = new Date($( "#lastAssimilationDate" ).val());
d2 = new Date($( "#lastAssimilationDateOver").val());
alert(monthDiff(d1, d2));

Check this JSFiddle

检查这个JSFiddle

Not sure Nanis popping, but I am able to see difference.

不确定Nan是否弹出,但我能够看到差异。

enter image description here

在此处输入图片说明

回答by Shoaib Fazlani

    function calcualteMonthYr(){
    var fromDate =new Date($('#txtFrom').val()); //datepicker (text fields)
    var toDate = new Date($('#txtTo').val()); // datepicker

     var months;
        months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
        months += toDate.getMonth();
        if (toDate.getDate() < fromDate.getDate())
        {
            months--;
        }
    $('#txtTimePeriod2').val(months);
}
// it also consider dates so you would get exact months ..