-1

I need to subtract two dates with the diff function of moment, the problem is that it does not recognize the diff function which sends me an error

var fechaActual         = new Date();
debugger;
var Datos               = traeIdEstado();

var FechaEstadoAnterior = Datos[0];
var idEstado            = Datos[1];

var dateA   = moment(fechaActual).format('YYYY-MM-DD');
var dateB   = moment(FechaEstadoAnterior).format('YYYY-MM-DD');

var d = dateA.diff(dateB, 'days',true); 
alert(d);

enter image description here

Dan-Dev
  • 8,957
  • 3
  • 38
  • 55
elsa
  • 101
  • 1
  • You're calling `diff` on a **string**. Your `dateA` and `dateB` are assigned the result of calling Moment's `format` function. That result is a string. – T.J. Crowder Dec 14 '16 at 19:11
  • Voting to close as *"This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers."* – T.J. Crowder Dec 14 '16 at 19:14
  • have you tried removing the format method call? I have a feeling it is returning an object that is different than what you expect. – Vinny Dec 14 '16 at 19:15
  • @T.J.Crowder I do not understand much how this function works, what would you advise me to do? – elsa Dec 14 '16 at 19:15
  • If you want to use `diff`, use it on a moment object, not a string. I can't help you with your end goal here because you haven't said what that end goal is. – T.J. Crowder Dec 14 '16 at 19:19

2 Answers2

1

The diff method only works with numbers, because the computer can't really tell the difference between strings. For this reason, you need to diff first, THEN format the result. Formatting doesn't really help the diff work in your example.

This Stack question Get hours difference between two dates should help you get the result you're looking for. You might have to convert the dates into hours to be able to get the diff, which are values it can use to compare.

Community
  • 1
  • 1
Ryan
  • 3,153
  • 2
  • 23
  • 35
  • *"The diff method only works with numbers"* ?!? Moment's [`diff`](http://momentjs.com/docs/#/displaying/difference/) works with `Date`, moment instances, and a bunch of other things, not just numbers. – T.J. Crowder Dec 14 '16 at 19:19
  • It only works with numerically calculable values, NOT strings. – Ryan Dec 14 '16 at 19:23
  • I suggest reviewing the documentation. It's perfectly happy if you pass `diff` a string as the first argument. (It parses it.) The problem in the question is that the OP is **calling** `diff` on a string. But it's not a string method. It's a Moment method. – T.J. Crowder Dec 14 '16 at 19:23
0

The solution to the problem was as follows

var dateA   = moment(fechaActual).format('YYYY-MM-DD');
var dateB   = moment(FechaEstadoAnterior).format('YYYY-MM-DD');

//var d = dateA.diff(dateB, 'days',true);

//alert(d);
var d = moment(dateA).diff(moment(dateB), 'day');
elsa
  • 101
  • 1