Calculate the difference between two dates in React Native

var msDiff = new Date("June 30, 2035").getTime() - new Date().getTime();    //Future date - current date
var daysTill30June2035 = Math.floor(msDiff / (1000 * 60 * 60 * 24));
console.log(daysTill30June2035);

If you manipulate many dates, maybe an external library like moment.js could be useful. There are multiple add-ons like the date range one.

Once installed, you need to create a range

const start = new Date(2011, 2, 5);
const end   = new Date(2011, 5, 5);
const range = moment.range(start, end);

Then could get the difference by doing something like

range.diff('months'); // 3
range.diff('days');   // 92
range.diff();         // 7945200000

Hope it could be useful :)


You can implement it yourself, but why would you? The solution to that already exists, and somebody else has taken care (and still is taking care) that it works as it should.

Use date-fns.

import differenceInDays from 'date-fns/difference_in_days';

If you really want to bash your head, you can get difference in milliseconds and then divide by number of milliseconds in a day. Sounds good to me, but I'm not 100% sure if it works properly.

const differenceInDays = (a, b) => Math.floor(
  (a.getTime() - b.getTime()) / (1000 * 60 * 60 * 24)
)

Tags:

React Native