如何获取2个日期之间的月份 [英] How to get the months between 2 dates

查看:168
本文介绍了如何获取2个日期之间的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery datepicker ,以获得2个日期。在我的情况下,我必须以这种格式获得日期 d-M-y 。我正在使用它,以便能够将值插入到 oracle 数据库中,而无需任何格式化。问题是我需要计算2个日期之间的月份。例如: 1-Oct-13 - 30-Oct-16

I'm using jquery datepicker in 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 oracle database without any formating. The problem is that I need to calculate the months between 2 dates. For example: 1-Oct-13 - 30-Oct-16.

这是我在js中获取日期的方法:

Here is how I'm getting the dates in my 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"
                        });
                    }),

上述日期分配给 2个变量 - lastAssimilationDate LastAssimDateOver

The above dates are assigned to 2 variables - lastAssimilationDate and LastAssimDateOver

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

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.

推荐答案

p>因为你提到你不应该改变格式我有一个解决方案。

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

在@TJ的帮助下Crowder的答案,我这样做了

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

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

查看这个 JSFiddle

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

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

这篇关于如何获取2个日期之间的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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