DEV Community

SeongKuk Han
SeongKuk Han

Posted on • Updated on

Antd Calendar Get the first date and the last date on the panel

Antd Calendar Get the first date and the last date on the panel


There is a calendar.

Antd_Calendar

Of course, 01 is the first date of July, and 31 is the last date of July. instead of this, you might want to get the first date and last date on the panel in some cases. June 26 and August 07.

Antd Calendar provides onPanelChange event. We will write code in the event. Antd adopted moment as a default date library. It's really easy to use for handling date. You can replace it with another date library though. (docs)


For getting the first date on the panel, just subtract the day number of the first date of the month. moment represent days as numbers.

Sunday(0) ~ Saturday(6)

The first date of July/2022 is Friday. It represents 5 as a day number. If you subtract 5 from the first date of July/2022, you will get 26/June/2022.

The number of dates on the panel is 42. Subtract the last date of the month and the day number of the first date from 42.

If it is July/2022 and subtract 42 - 5(the day number of the first date) - 31(the last date of July), you will get six. Add the number to the last date of July, it is 06/August/2022.


Here's the code.

import { useState } from "react";
import moment, { Moment } from "moment";
import { Calendar } from "antd";

const getFirstDateAndLastDateOnThePanel = (date: Moment) => {
  const firstDate = moment(date).startOf("month");
  const lastDate = moment(date).endOf("month");

  const firstDateDay = firstDate.day();
  firstDate.subtract(firstDateDay, "days");
  lastDate.add(42 - Number(lastDate.format("DD")) - firstDateDay, "days");

  return {
    firstDate,
    lastDate,
  };
};

function App() {
  const [date, setDate] = useState(moment());

  const handlePanelChange = (date: Moment) => {
    const { firstDate, lastDate } = getFirstDateAndLastDateOnThePanel(date);

    console.log({
      firstDate: firstDate.format("YYYY-MM-DD"),
      lastDate: lastDate.format("YYYY-MM-DD"),
    });
  };

  return (
    <div>
      <Calendar
        value={date}
        onChange={setDate}
        onPanelChange={handlePanelChange}
      />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

execution_page


I hope this will be helpful for someone.
Happy Coding!

Top comments (0)