Search code examples
javascriptfunctiontime-format

Javascript conditional time range format function


I am using React for my frontend app.

I have two different time format of data.

One is like this 08-10 and another one is like this 05:00-05:30.

Most of the time format data is like this 08-10, few are like 05:00-05:30.

After getting the time date data, I used map function and pass to my time-format helper function, In my browser I want to display my data like this 05:00-05:30.

My helper function do like this: if the time looks like this 08-10 then the function will split it into two then add : and convert them into 08:00-10:00. As I mentioned I have two different time format data, when the data come like this 05:00-05:30 then my helper function convert them like 0500-0530.

I want to render my function conditionally if the data is like 05:00-05:30 then return as it is, if the data is like this 08-10 then convert them into 08:00-10:00. I don't know how to do that in my helper function.

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());


Solution

  • Your code seemed to work if you call it correctly

    I assume you want this though

    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);