Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

date - Javascript month difference

How do I calculate difference in months in Javascript?

Please note there are similar questions such as: What's the best way to calculate date difference in Javascript

But these are based around MS difference, when some months have different number of days than others!

Any easy way to calculate month difference between 2 dates?

Just to be clear, I need to know how many months the dates span, for example:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));

getMonth minus getMonth gives you the month difference between the dates two months.

We then multiply 12 by the number of years difference and add this to the result giving us the full month span.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...