Javascript 条件时间范围格式函数

Javascript conditional time range format function

我正在为我的前端应用程序使用 React。

我有两种不同时间格式的数据。

一个是这样的08-10还有一个是这样的05:00-05:30.

大部分时间格式数据是这样的08-10,很少是这样的05:00-05:30.

获取时间日期数据后,我使用 map 函数并传递给我的 time-format 辅助函数,在我的浏览器中,我想像这样显示我的数据 05:00-05:30

我的辅助函数是这样做的:如果时间看起来像这样 08-10 那么该函数将把它分成两部分然后添加 : 并将它们转换为 08:00-10:00。正如我提到的,我有两个不同的时间格式数据,当数据像这样 05:00-05:30 时,我的辅助函数将它们转换为 0500-0530.

我想有条件地渲染我的函数,如果数据像 05:00-05:30 那么 return 就这样,如果数据像这样 08-10 然后将它们转换成 08:00-10:00.我不知道如何在我的辅助函数中执行此操作。

const toTimeRangeFormat = (range) => {
  console.log(range);

  const [start, end] = range?.split("-");
  const toFourDigitTime = (time) => {
    const [hours, minutes] = time.split(":");
    return hours.padStart(2, "0") + (minutes ? minutes : ":00");
  };

  if (start && end) {
    return toFourDigitTime(start) + " - " + toFourDigitTime(end);
  }

  return range;
};

const time = ["08-10", "05:00-05:30"];

time.filter((i) => {
  if (typeof i === "string") {
    return toTimeRangeFormat(i);
  }
});

console.log(toTimeRangeFormat());

如果调用正确,您的代码似乎可以正常工作

不过我假设你想要这个

const re = /(\d{2}):?(\d{2})?/; // take the (set of) two digits from NN:NN, NNNN or NN - the ? means optional
const toFourDigitTime = time => {
  const [hours, minutes] = time.match(re).slice(1); // ignore result[0]
  return `${hours.padStart(2, "0")}:${minutes ? minutes : "00"}`;
};

const toTimeRangeFormat = (range) => {
  const [start, end] = range ?.split("-");
  if (start && end) {
    return toFourDigitTime(start) + " - " + toFourDigitTime(end);
  }

  return range;
};

const time = ["08-10", "05:00-05:30"];

const time1 = time.map(str => toTimeRangeFormat(str));

console.log(time1);