jquery - Calculate number of days between two dates with momentsjs -


i got 2 dates stored inside var (created date picker). format these using moments.js

i want calculate number of days between these 2 fields , store number inside var days. code far:

// when clicks submit button, create url stored in var url. $(".book_submit").on('click', function(e){    // datepicker , input fields data   var = $('.from').val();   var = $('.to').val();    // can format "from" var way want    = moment(from, "dd.mm.yyyy");   = moment(from).format("yyyy-mm-dd");    // can format "to" var way want   = moment(to, "dd.mm.yyyy");   = moment(to).format("yyyy-mm-dd");    // want store number between 2 dates in var "days", place inside link below. have found ".diff(to, 'days') in moments documentation.    //days = from.diff(to, 'days');   // =1    var url = "https://mycustomlink&days= " + days + "";  }); 

i can't from.diff(to, 'days') work , store inside variable. have tried set like:

var days = from.diff(to, 'days'); 

how can store difference between these days inside var days? appreciate suggestion.

apart .diff(), use moment durations: http://momentjs.com/docs/#/durations/

edit: don't know thinking then. @aedm pointing out. there no need of duration here, creating time spans.

.diff works intended, have make sure using correct format parse dates.

example fiddle: https://jsfiddle.net/abhitalks/md4jte5d/

example snippet:

$("#btn").on('click', function(e) {  	var fromdate = $('#fromdate').val(),     		todate = $('#todate').val(),   		from, to, druation;      	from = moment(fromdate, 'yyyy-mm-dd'); // format in have date  	to = moment(todate, 'yyyy-mm-dd');     // format in have date      	/* using diff */  	duration = to.diff(from, 'days')       	  	/* show result */  	$('#result').text(duration + ' days');      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>  from: <input id="fromdate" type='date' />  to: <input id="todate" type='date' />&nbsp;&nbsp;  <button id="btn">submit</button><hr />  <p id="result"></p>


as see in code, have comments this:

// can format "from" var way want 

no. cannot format dates way you want. have use format in date parsing in. in example, using html5 date, returned date in yyyy-mm-dd format, hence using format. in case, determine format textboxes return dates in, , use format.

you may omit format altogether, if sure returned date in standard format.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -