1. 首先引入antd
yarn add antd | npm i antd
2. 在页面中引入日期组件
import { DatePicker } from 'antd'
3. 本次做一个默认上个月最后一天,选择具体月份时,展示选择月最后一天。效果如图:
import dayjs from 'dayjs'
<DatePicker
picker="month"
style={{ width: '100%' }}
defaultValue={dayjs(getLastEndDate())}
format={customFormat}
>
4. 使用 format
属性,可以自定义日期显示格式。如上图使用月份选择器,但实际展示YYYY-MM-DD形式。
// 自定义日期显示格式
const customFormat: DatePickerProps['format'] = value => {
return `${getEndDate(value)}`;
};
5. 此处使用Dayjs获取上月,当月最后一天,也可用js实现。
import dayjs from 'dayjs'
// 获取上月最后一天
export function getLastEndDate(value: Dayjs | Date = new Date()) {
// 获取上月
const month = dayjs(value).subtract(1, 'month').format('YYYY-MM');
// 获取上月最后一天
return getEndDate(month);
}
import dayjs from 'dayjs'
// 获取默认月份最后一天,传入月份
export function getEndDate(month: string | Dayjs) {
// 获取最后一天
return dayjs(month).endOf('month').format('YYYY-MM-DD');
}
6. 注意,时间选择器可能会出现一半中文一半英文问题,实际是因为dayjs没有使用中文包。可在项目入口文件index.tsx中加入以下代码,即可解决。
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import zhCN from 'antd/es/locale/zh_CN';
// 解决日期选择器一半中文一半英文问题
dayjs.locale('zh-cn');
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<ConfigProvider locale={zhCN}>
<HashRouter>
<App />
</HashRouter>
)}
</ConfigProvider>