Mohamed Saqer
Mohamed Saqer

Reputation: 177

Calculate the difference between two dates in React Native

I need to calculate the difference between two dates in days

i bring today date: new Date().toJSON().slice(0, 10) = 2019-04-17 and the other date in the same form

Upvotes: 10

Views: 34370

Answers (5)

Sayan Dey
Sayan Dey

Reputation: 472


Use differenceInDays, parseISO from "date-fns"


import DateTimePicker from "@react-native-community/datetimepicker";
import { differenceInDays, parseISO } from "date-fns";

 let day = differenceInDays(
        parseISO(your end date),
        parseISO(yout first Date)
      );
console.log("differenceInDays",differenceInDays)

Upvotes: 0

Ben
Ben

Reputation: 155

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 :)

Upvotes: 2

Zobia Kanwal
Zobia Kanwal

Reputation: 4723

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);

Upvotes: 13

jokka
jokka

Reputation: 1912

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)
)

Upvotes: 4

Rodrigo
Rodrigo

Reputation: 234

var d1 = new Date("2019/04/17") //firstDate
var d2 = new Date("2011/02/01") //SecondDate
var diff = Math.abs(d1-d2); //in milliseconds

Upvotes: 1

Related Questions