如何使用含年月日时分的DatePicker?如何配置其显示年、AM/PM等元素?
Hey there! I’ve tackled this exact DatePicker setup before, so let’s walk through how to get your component displaying all the date/time segments you need.
1. Using a DatePicker with Year, Month, Day, and Hour
Most modern DatePicker components let you specify which date segments to show via a format string and a picker type prop. Here’s a concrete example using Ant Design (one of the most popular React UI libraries)—the logic translates to most frameworks with minor tweaks:
import { DatePicker } from 'antd'; import dayjs from 'dayjs'; // DatePicker showing year, month, day, and hour const HourlyDatePicker = () => ( <DatePicker picker="datetime" // Enables date + time selection format="YYYY-MM-DD HH" // Defines the display format style={{ width: 200 }} placeholder="Pick date & hour" /> );
Let’s break down the format tokens here:
YYYY: 4-digit year (e.g., 2024)MM: 2-digit month (e.g., 05 for May)DD: 2-digit day (e.g., 15)HH: 24-hour format (swap withhhif you want 12-hour time with AM/PM)
2. Adding Seconds and AM/PM to Your DatePicker
To include seconds and AM/PM, you just need to update the format string and ensure your component supports 12-hour time display. Here’s how to adjust the Ant Design example:
import { DatePicker } from 'antd'; import dayjs from 'dayjs'; import 'dayjs/plugin/advancedFormat'; // Needed for AM/PM formatting dayjs.extend(advancedFormat); // Full datetime picker with AM/PM const FullDateTimePicker = () => ( <DatePicker picker="datetime" format="YYYY-MM-DD hh:mm:ss A" // Adds minutes, seconds, and AM/PM style={{ width: 250 }} placeholder="Pick full datetime" /> );
Updated format breakdown:
hh: 12-hour hour (e.g., 03 instead of 15 for 3 PM)mm: 2-digit minutesss: 2-digit secondsA: Uppercase AM/PM (useafor lowercase "am/pm")
For Material UI Users
If you’re working with Material UI, the setup is similar but uses a views prop to explicitly define which segments to render:
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; const MUIDateTimePicker = () => ( <LocalizationProvider dateAdapter={AdapterDayjs}> <DateTimePicker label="Full Datetime" format="YYYY-MM-DD hh:mm:ss A" views={['year', 'month', 'day', 'hours', 'minutes', 'seconds']} // Explicitly enable all segments /> </LocalizationProvider> );
General Tips for Any Library
No matter which UI library you’re using, the core steps are:
- Find the component’s date format configuration (usually called
format,displayFormat, ortimeFormat) - Use the library’s supported format tokens to include all required segments (year, month, day, hour, minute, second)
- Enable 12-hour time mode if you need AM/PM (check docs for specific props like
ampmor usinghhinstead ofHHin the format)
内容的提问来源于stack exchange,提问作者kiran

