iamspauljamez
iamspauljamez

Reputation: 287

Moment JS gives wrong date when I use diff

I've been working to get the difference of two dates using moment JS.

test1 = new Date("01/12/2015")
test2 = new Date("12/12/2014")


get_diff = moment.duration(moment(test1,"DD/MM/YYYY").diff(moment(test2,"DD/MM/YYYY")))
result_diff = get_diff.asDays()
console.log result_diff

It gives: 365. It supposed to give 31 days.

Upvotes: 2

Views: 1030

Answers (4)

jbeck
jbeck

Reputation: 2254

You should be instantiating the moment objects with the strings themselves:

var test1 = moment('01/12/2015', 'MM/DD/YYYY');
var test2 = moment('12/12/2014', 'MM/DD/YYYY');

var get_diff = moment.duration(test1.diff(test2));
var result_diff = get_diff.asDays();

Upvotes: 1

epascarello
epascarello

Reputation: 207501

The way you have it written, you should not be using JS date objects and you have the month and days switched.

test1 = "01/12/2015";
test2 = "12/12/2014";

get_diff = moment.duration(moment(test1,"MM/DD/YYYY").diff(moment(test2,"MM/DD/YYYY")))
result_diff = get_diff.asDays()
console.log(result_diff)

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You don't need to use durations for this and also no need to convert to "DD/MM/YYYY" format. Just use diff method with "days" as the second parameter:

var test1 = new Date("01/12/2015");
var test2 = new Date("12/12/2014");

var result_diff = moment(test1).diff(moment(test2), "days"); // 31

Upvotes: 1

Just code
Just code

Reputation: 13801

I suppose you should change your code to get days difference

var date1 = new Date("01/12/2015")
var date2 = new Date("12/12/2014")
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

Upvotes: 0

Related Questions