如何使用 moment.js 计算没有周末的两个日期之间的差异
How to calculate the different between two Dates whiteout weekend day Using moment.js
如何通过在 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]);
您可以像这样在您的代码中实现 :
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>
);
}
如何通过在 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]);
您可以像这样在您的代码中实现
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>
);
}