JavaScript date difference calculation

Requirement::

Once upon I was require to get difference between date like below example:-
Get Month Difference or get difference between two dates or Get Year Difference or Get Weeks Difference or Get Days Difference..

Solution:-

Create date string format as “mm/dd/yyyy”. Then create date object of this string as below mention:-

1
2
3
4
5
6
<script type="text/javascript">// <![CDATA[
        var fromDateString = "12/20/2004"
        var fromDate = new Date(fromDateString);
        var toDateString = "12/20/2011"
        var toDate = new Date(toDateString);
// ]]></script>

Now Pass these dates to below functions:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script type="text/javascript">// <![CDATA[
        function DaysDiff(d1, d2) {
            var t2 = d2.getTime();
            var t1 = d1.getTime();
 
            return parseInt((t2 - t1) / (24 * 3600 * 1000));
        }
 
        function WeekDiff (d1, d2) {
            var t2 = d2.getTime();
            var t1 = d1.getTime();
 
            return parseInt((t2 - t1) / (24 * 3600 * 1000 * 7));
        }
 
        function MonthsDiff (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);
        }
 
        function YearDiff (d1, d2) {
            return d2.getFullYear() - d1.getFullYear();
        }
// ]]></script>

Tip:
d1.getMonth() give results like 00 for Jan, 01 for Feb …. 11 for Dec.

Thanks!
Infoyen

calendarMay 14, 2012 · cardInfoyen · commentsNo Comments
tagTags: , , , , , ,  · Posted in: JavaScript

Leave a Reply

Spam Protection: , required

myworldmaps infoyen