0

how can i get the different between two dates without weekend days , by using Moment.js in react . this is my code

useEffect(() => {
    if (dates && dates.length > 1) {
      const startDate = dates[0];
      const endDate = dates[1];

      
      if (startDate && endDate) {
        const diff = endDate.startOf('day').diff(startDate.startOf('day'), 'days') + 1;
        
      }
//this will return to me the different between two dates with Weekend Days 
    }
  }, [dates]);
Ammar ALSananni
  • 141
  • 1
  • 9

1 Answers1

1

You can implement this solution in your code like this:

import { useEffect, useState } from 'react';
import moment from 'moment';

import "./styles.css";

const dates = [moment('08-09-2021'), moment('08-16-2021')];

function workday_count(start,end) {
  const first = start.clone().endOf('week');
  const last = end.clone().startOf('week');
  const days = last.diff(first,'days') * 5 / 7;
  const wfirst = first.day() - start.day();
  if(start.day() === 0) --wfirst;
  const wlast = end.day() - last.day();
  if(end.day() === 6) --wlast;
  return wfirst + Math.floor(days) + wlast;
} // 

export default function App() {
  const [diff, setDiff] = useState(0);

  useEffect(() => {
    if (dates && dates.length > 1) {
      const startDate = dates[0];
      const endDate = dates[1];

      
      if (startDate && endDate) {
        const difference = workday_count(startDate.startOf('day'), endDate.startOf('day'));
        setDiff(difference); 
      }
    }
  }, []);
  return (
    <div className="App">
      <h1>Diff: {diff}</h1>
    </div>
  );
}

Codesandbox

Girgetto
  • 1,010
  • 9
  • 19