【问题标题】:How to calculate the different between two Dates whiteout weekend day Using moment.js [duplicate]如何使用moment.js计算两个日期之间的差异
【发布时间】:2021-08-09 14:40:48
【问题描述】:

如何通过在 react 中使用 Moment.js 来获得没有周末的两个日期之间的差异。这是我的代码

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

【问题讨论】:

    标签: reactjs momentjs


    【解决方案1】:

    您可以像这样在代码中实现this solution

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 2011-05-21
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 2010-10-15
      相关资源
      最近更新 更多