简体   繁体   中英

Add / Remove 1 day with Moment.js in React

I have a div with 2 dates inside, for example (< march 25th - march 26th >), and there are 2 arrows "<" and ">"

If a user presses the "<" arrow, I need to remove 1 day to the 2 dates : (< march 25th - march 26th >) becomes (< march 24th - march 25th >),

and if a user presses the ">" arrow, I need to add 1 day to the 2 dates : (< march 25th - march 26th >) becomes (< march 26th - march 27th >),

I stored the 2 dates in hooks, and by default, the firstValue is the day of today and the secondValue is 1 week later

const [firstValue, setFirstValue] = useState(
    moment(new Date()).format("dddd Do MMMM YYYY")
  );
const [secondValue, setSecondValue] = useState(
    moment(new Date())
      .add(1, "weeks")
      .format("dddd Do MMMM YYYY")
);

I tried this when the user presses the "<" arrow :

function previousDay() {
    console.log(firstValue, secondValue);
    setFirstValue(moment(firstValue).remove(1, "days"));
    setSecondValue(moment(secondValue).remove(1, "days"));
}

but I have the error

TypeError: moment__WEBPACK_IMPORTED_MODULE_2___default(...)(...).remove is not a function

Can somebody know how can I do that

Based on my comments, I'd suggest the following changes:

const [firstValue, setFirstValue] = useState(
    moment(new Date()) // remove .format() here
  );
const [secondValue, setSecondValue] = useState(
    moment(new Date())
      .add(1, "weeks")
);

On your render:

render() {
  <>
    ...
    ...
    {firstValue.format("dddd Do MMMM YYYY")}
  </>
}

And your function should be something like:

function previousDay() {
    setFirstValue(firstValue.subtract(1, "days")); // don't need to moment() anymore
    setSecondValue(secondValue.subtract(1, "days"));
}

Change to :

function previousDay() {
    console.log(firstValue, secondValue);
    setFirstValue(moment(firstValue).subtract(1, "days"));
    setSecondValue(moment(secondValue).subtract(1, "days"));
}

Because "remove" is not a valid property of [Moment object].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM