MomentJS Day diff dates only excluding time
Asked Answered
G

2

21

Is there a way of comparing 2 dates without time with momentJS?

I've tried various formats, but can't seem to get it to work.

I have it working fine with dateTime:

var ExpiryDate = new Date("11/13/2014 11:13:00");
var daysDiff = moment(ExpiryDate).diff(moment(Date.now()), 'days');

I'm looking to get the result to be 14 days no matter what time of day.

Thanks

Garnet answered 3/11, 2014 at 11:11 Comment(1)
if you want to add a day based on time, then compare the timepart of two dates and add, if needed...Adequate
S
48

You can use the startOf function to remove the time components of both dates

moment(ExpiryDate).startOf('day').diff(moment(Date.now()).startOf('day'), 'days');
Serotherapy answered 3/11, 2014 at 11:16 Comment(1)
Note: This method alters the original date. For 'day' it literally sets minutes, seconds and hours for the existing object to 0 (so it is very fast). In this case you're creating a new object and altering it so there are no actual side effects but if you were to do ExpiryDate.startOf('day') without creating a new moment then it would change the original. Here's the implementation if you're curious : github.com/moment/moment/blob/…Krummhorn
N
0

You can generalize to a function that prevents mutating the original objects:

/** Returns true if the first date is before the second one. */
function dateIsBefore(moment1: Moment, moment2: Moment): boolean {
  return moment1.clone().startOf('day') < moment2.clone().startOf('day')
}
Nadler answered 5/9, 2022 at 22:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.