兼容antd的日期选择:开始为00:00:00点,结束为23:59:59

608 阅读1分钟

在使用久远的antd 4.x版本开发过程中,发现使用的日期选择组件无法设置选择开始的时间和结束,故写一个方法来实现,开始为00:00:00点,结束为23:59:59,可修改自定义,逻辑解析在下面,time为我提交时做的处理,使用时如下:

--js
  const handletime = (_, time) => {
    if (time.length === 2 && time[1]) {
      setTime([convertToTime(time[0]), convertToTime(time[1], false)])
    } else {
      setTime([])
    }
  }

--jsx
  <RangePicker format="YYYY-MM-DD" onChange={handletime} />

下面是convertToTime的实现,在convertToTime函数中,该input参数允许您提供日期字符串或时间戳。然后,该typeof函数使用检查确定输入的类型。如果输入是字符串,则它使用new Date构造函数创建一个新Date对象,并将字符串作为参数。如果输入是数字,则假定它是时间戳,并使用构造函数以时间戳作为参数创建新Date对象。

根据toMidnight参数的值,该setHours函数使用Date对象的方法将时间设置为午夜 (0:00) 或 23:59:59。

下面是代码摘要:

function convertToTime(input, toMidnight) {
  let date;
  if (typeof input === 'string') {
    date = new Date(input);
  } else if (typeof input === 'number') {
    date = new Date(input);
  }
  if (toMidnight) {
    date.setHours(0, 0, 0, 0);
  } else {
    date.setHours(23, 59, 59, 0);
  }
  return date.getTime();
}

const inputDateString = '2022-01-01'; // Example date string
const inputTimestamp = 1641024000000; // Example timestamp

const outputTimestamp1 = convertToTime(inputDateString, true);
console.log(outputTimestamp1); // Timestamp representing 0:00 (midnight) of the given date string

const outputTimestamp2 = convertToTime(inputTimestamp, false);
console.log(outputTimestamp2); // Timestamp representing 23:59:59 of the given timestamp

 

现在,您可以使用该convertToTime函数根据需要将日期字符串或时间戳转换为午夜 (0:00) 或 23:59:59。