Marian Rick Marian Rick - 3 months ago 36x
jQuery Question

Calculate number of days between two dates with momentsjs

I got two dates stored inside a var (created by a date picker). To format these I am using moments.js

I want to calculate the number of days between these two fields and store this number inside a var

. This is my code so far:

// When someone clicks my submit button, I create an url stored in the var url.
$(".book_submit").on('click', function(e){

// I get the datepicker and input fields data
var from = $('.from').val();
var to = $('.to').val();

// I can format the "from" var the way I want
from = moment(from, "DD.MM.YYYY");
from = moment(from).format("YYYY-MM-DD");

// I can format the "to" var the way I want
to = moment(to, "DD.MM.YYYY");
to = moment(to).format("YYYY-MM-DD");

// I want to store the number between the two dates in the var "days", to place it inside my link below. I have found ".diff(to, 'days') in the moments documentation.

//days = from.diff(to, 'days'); // =1

var url = "https://mycustomlink&days= " + days + "";


I can't get
from.diff(to, 'days')
to work and store it inside a variable. I have tried to set it like:

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

How can I store the difference between these to days inside my var
? I appreciate any suggestion.


Apart from .diff(), you could also use moment durations:

Edit: Don't know what was I thinking back then. Thanks @aedm for pointing it out. There is no need of duration here, which is for creating time spans.

.diff works as intended, just that you have to make sure you are using the correct format to parse the dates.

Example Fiddle:

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 which you have the date
	to = moment(toDate, 'YYYY-MM-DD');     // format in which you have the date
	/* using diff */
	duration = to.diff(from, 'days')     
	/* show the result */
	$('#result').text(duration + ' days');
<script src=""></script>
<script src=""></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 I see in your code, you have comments like this:

// I can format the "from" var the way I want

No. You cannot format the dates the way you want. You have to use the format in which the date you are parsing is in. In my example, as I am using the HTML5 date, the returned date is in the yyyy-mm-dd format, hence using that format. In your case, determine what format your textboxes return the dates in, and use that format.

You may also omit the format altogether, if you are sure that the returned date is in a standard format.