You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MUI X Date and Time Picker中禁用分钟并将秒数锁定为0

解决MUI X DateTimePicker选择时间自动生成随机秒数问题

实现逻辑

要固定秒数为0,只需要加两步配置即可:

  • 通过onChange钩子在值变更时统一处理时间对象,将秒数固定为0,也可同时固定分钟为0保证取值严格符合整点要求
  • 配合inputFormat属性自定义输入框展示格式,隐藏不需要的分钟、秒字段,和交互逻辑对齐

修改后代码示例

这里以搭配date-fns日期库为例(MUI X默认适配该库),如果用其他日期库替换对应时间处理方法即可:

// 首先引入时间处理方法
import { setSeconds, setMinutes } from 'date-fns'

<Controller
  name="checkOut"
  control={control}
  render={({ field }) => (
    <Grid item xs={12} md={12}>
      <FormControl sx={FCWidth}>
        <DateTimePicker
          {...field}
          toolbarFormat=""
          label="Check Out"
          name="checkOut"
          disablePast={true}
          minutesStep={60}
          // 新增:自定义输入格式,只展示到小时,不显示分钟秒
          inputFormat="yyyy-MM-dd HH"
          // 新增:处理时间值,固定分钟、秒为0
          onChange={(newValue) => {
            if (newValue) {
              // 先固定分钟为0,再固定秒和毫秒为0
              const processedValue = setSeconds(setMinutes(newValue, 0), 0, 0)
              field.onChange(processedValue)
            } else {
              field.onChange(null)
            }
          }}
          renderInput={(params) => <TextField {...params} />}
        />
        <FormHelperText error={true}>
          {errors.checkOut?.message}
        </FormHelperText>
      </FormControl>
    </Grid>
  )}
/>

原生JS实现方案

如果不想引入额外日期库,也可以用原生Date方法处理:

onChange={(newValue) => {
  if (newValue) {
    const processedDate = new Date(newValue)
    processedDate.setMinutes(0)
    processedDate.setSeconds(0, 0)
    field.onChange(processedDate)
  } else {
    field.onChange(null)
  }
}}

原有效果参考:
效果展示图

内容的提问来源于stack exchange,提问作者ArkaBarua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:24:04