2

I am trying to find a difference in months between two moment objects. I did as follows:

const current = moment()
const future = moment().add('324523546345634563456345','months')
const diff = future.diff(current, 'months')

The diff comes out as 0. Why is that? Is there a different way to handle large numbers like 324523546345634563456345?

Amanda
  • 2,013
  • 3
  • 24
  • 57

1 Answers1

3

Short answer: your input exceeds the limitations of JavaScript's built-in integer and Date types. To do calculations with such large numbers, use type BigInt. (Most date libraries like MomentJS won't support BigInt, one of the reasons being regular integers provide a reasonable range of dates.)


The largest integer that can be represented by JavaScript built-in numbers is 9,007,199,254,740,991. Floating point numbers go much higher, but probably don't make sense for this type of use case (there would be too many floating point gaps).

Your input: 324,523,546,345,634,563,456,345 is many orders of magnitude greater than what JavaScript built-in integers support. This is even before considering the additional orders of magnitude after converting months to milliseconds.

Frankly, I'm surprised the result was 0 and not NaN.

Furthermore, I believe MomentJS internally uses the built-in JavaScript Date type. The max date is about the year 275,760. Your input would require support for a year way, way past this year. In fact, your input is greater than the age of the universe.

If you really need to make such a calculation, you could use BigInts. You'll probably have to do the calculations manually because I don't think any time-related library will support such large dates.

Leftium
  • 16,497
  • 6
  • 64
  • 99
  • I think moment's duration can handle the large numbers. Not sure why the discrepancy exists. – Amanda May 31 '19 at 07:41