Balu
Balu

Reputation: 564

How i get days accurately in Moment.js

This is my code for getting days difference from given dates. I need the days accurately, Here my correct days different is '2' but i am getting 1. i am using moment.js for this operation in angular. This is not taking time . I need time to take for getting result. I am using this code in calendar so i need to take time too.

var startdate=new Date('2017-12-30 06:00:00');
var enddate=new Date('2018-01-01 01:00:00');

var diff=  moment(enddate).diff(startdate, "days");
console.log(diff)

Upvotes: 0

Views: 897

Answers (4)

vicky patel
vicky patel

Reputation: 705

var startdate=new Date('2017-12-30 06:00:00');
var enddate=new Date('2018-01-01 01:00:00');
console.log( moment(enddate).diff(startdate, 'days'))
console.log( moment(enddate).diff(startdate, 'weeks'))
console.log( moment(enddate).diff(startdate, 'hours')) 
console.log( moment(enddate).diff(startdate, 'minutes'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Upvotes: 0

Andreas
Andreas

Reputation: 21881

Difference 1.0.0+

...
By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned a number rounded to the nearest integer, not a truncated number.

var startdate = new Date('2017-12-30 06:00:00');
var enddate = new Date('2018-01-01 01:00:00');

var diff = moment(enddate).diff(startdate, "days", true);

console.log(diff);            // 1.7916666666666667
console.log(Math.ceil(diff)); // 2
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Upvotes: 1

Soulbe
Soulbe

Reputation: 554

Try using startOf, to remove time part of both dates.

moment(enddate).startOf('day').diff(moment(startdate).startOf('day'), 'days');

Upvotes: 3

gurvinder372
gurvinder372

Reputation: 68393

Try this vanilla JS solution

var numberOfDays = Math.ceil( ( enddate.getTime() - startdate.getTime() ) 
                     / ( 1000*60*60*24 ));

Demo

var startdate=new Date('2017-12-30 06:00:00');
var enddate=new Date('2018-01-01 01:00:00');
var numberOfDays = Math.ceil( ( enddate.getTime() - startdate.getTime() ) 
                     / ( 1000*60*60*24 ));
console.log( numberOfDays );

Upvotes: 1

Related Questions