Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - 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);
question from:https://stackoverflow.com/questions/65599474/why-momentjs-is-give-wrong-results

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...