Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the difference between two dates in React Native

Tags:

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

like image 365
Mohamed Saqer Avatar asked Apr 16 '19 23:04

Mohamed Saqer


People also ask

How do you calculate time between two dates in react?

Copy Code import { durationInMonths } from '@progress/kendo-date-math'; const start = new Date(2020, 1, 20); const end = new Date(2020, 10, 4); const duration = durationInMonths(start, end); // Returns the duration in months, `9`.


2 Answers

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);
like image 109
Zobia Kanwal Avatar answered Sep 21 '22 02:09

Zobia Kanwal


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)
)
like image 41
jokka Avatar answered Sep 25 '22 02:09

jokka