I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) { var start = $find('<%=StartWebDatePicker.ClientID%>').get_value(); var end = $find('<%=EndWebDatePicker.ClientID%>').get_value(); var oneDay=1000 * 60 * 60 * 24; var difference_ms = Math.abs(end.getTime() - start.getTime()) var diffValue = Math.round(difference_ms / oneDay); }
Can anyone tell me how I can get exact difference?
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]); var b = moment([2007, 0, 28]); a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
a/b.startOf('day')
and/or a/b.endOf('day')
to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments). true
to get a floating point diff which you can then Math.floor
, Math.ceil
or Math.round
as needed.'seconds'
instead of 'days'
and then dividing by 24*60*60
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With