Sam Tumuli
Sam Tumuli

Reputation: 15

Why momentjs is give wrong results

i have this code in moment.js.its work well,but i have one question.Example,today date is 06/01/2021 and with value 06/01/2021 of start DIV it give me result 0,same if i set 07-01-2021,it give me result of 0 .But if i set 08-01-2021 ,then it give me 1 (must be 2).i think if i set tomorrow date (07-01-2021) i must return value of 1,but i receive 0,,,why? is there a way to receive 1? thank you for explain and help me.

MY HTML

<div id="start">07-01-2021</div>
<div id='result'></div>

javascript,monent.js

var inputDiv = document.getElementById('start');
var startDate = moment();
var endDate = moment(inputDiv.innerHTML, "DD/MM/YYYY");
var result = 'Diff: ' + endDate.diff(startDate, 'days');
$('#result').html(result);

Upvotes: 0

Views: 96

Answers (2)

astangelo
astangelo

Reputation: 627

Moment is going to work as a datetime, so both of your dates are going to have a time associated with them.

var inputDiv = document.getElementById('start');
var endDate = moment(inputDiv.innerHTML, "DD/MM/YYYY"); // time of midnight (start of day), locally
var startDate = moment();  // time you run the code

So, endDate.diff(startDate, 'days') is going to calculate something akin to (tonight at midnight[locally]) - (today, midday[locally]). There is no full day difference in that equation.

Try either endDate.endOf('day').diff(startDate, 'days'), or better yet endDate.endOf('day').diff(startDate.endOf('day'), 'days').

Or you could just set var startDate = moment().startOf('day'); and use the code you have now.

Upvotes: 2

Ferman Quliyev
Ferman Quliyev

Reputation: 46

Try "DD-MM-YYYY" instead of "DD/MM/YYYY"

Upvotes: 1

Related Questions