how to calculate number of days between two dates using jquery [Answered]RSS

3 replies

Last post Jan 03, 2015 06:52 AM by Nadeem157

• priya15_pate...

Member

19 Points

164 Posts

how to calculate number of days between two dates using jquery

Dear All,

I have a two date time picker which stores the date in  "31-Dec-2014" format. now i want to calculate difference between to dates in NO OF DAYS.

how can i do it using jquery?

dates two between JQuery difference

• JoyceW

Contributor

4070 Points

1575 Posts

Re: how to calculate number of days between two dates using jquery

Pass you dates to this function like this:  showDays('1/1/2014','12/25/2014')

``` function showDays(firstDate,secondDate){

var startDay = new Date(firstDate);
var endDay = new Date(secondDate);
var millisecondsPerDay = 1000 * 60 * 60 * 24;

var millisBetween = startDay.getTime() - endDay.getTime();
var days = millisBetween / millisecondsPerDay;

// Round down.

}```

• Fei Han - MS...

All-Star

38916 Points

5607 Posts

Microsoft

Re: how to calculate number of days between two dates using jquery

Jan 02, 2015 02:16 AM|Fei Han - MSFT|LINK

Hi priya,

You could refer to those similar issues to calculate the number of days between two dates.

Hope it will be helpful for you.

Best Regards,

Fei Han

MSDN Community Support

Contributor

2106 Points

2551 Posts

Re: how to calculate number of days between two dates using jquery

Hi Priya,

You can go with the solution given by the http://forums.asp.net/members/Fei%20Han%20-%20MSFT.aspx

Also you can do sonmething like this.:-

HTML of the textboxes:-

```<input class='fromdate' />
<input class='todate' />
<input class='calculated' />   //Result will be here
<input class='minim' />```

Also see the javascript code for calculating the no if days..!!

```<script src="http://code.jquery.com/jquery-1.9.1.js"></script>   // default jquery plugin.
<script type="text/javascript">
\$('.fromdate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
\$('.todate').datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true,
});
\$('.fromdate').datepicker().bind("change", function () {
var minValue = \$(this).val();
minValue = \$.datepicker.parseDate("yy-mm-dd", minValue);
\$('.todate').datepicker("option", "minDate", minValue);
calculate();
});
\$('.todate').datepicker().bind("change", function () {
var maxValue = \$(this).val();
maxValue = \$.datepicker.parseDate("yy-mm-dd", maxValue);
\$('.fromdate').datepicker("option", "maxDate", maxValue);
calculate();
});

function calculate() {
var d1 = \$('.fromdate').datepicker('getDate');
var d2 = \$('.todate').datepicker('getDate');
var oneDay = 24*60*60*1000;
var diff = 0;
if (d1 && d2) {

diff = Math.round(Math.abs((d2.getTime() - d1.getTime())/(oneDay)));
}
\$('.calculated').val(diff);
\$('.minim').val(d1)
}</script>```

See the running JS fiddle for your reference:-

http://jsfiddle.net/vxb72b1L/2/

Do let me know whether it works or not.!