0

Using date-fns, how it could be converted below piece of code using date-fns. Basically, inputs are like, '01:40:20 PM' or '1:4:2 PM' or '3:2 PM' OR '03:2 PM' And expected output to be consistent like, '03:02:00 PM' , in hh:mm:ss A format.

I could not find any particular method that allows format with time only.

Using moment js, it works fine as below:

 if (moment(timeString, ['h:m:s A', 'h:m A'], true).isValid()) {
    return moment(timeString, 'hh:mm:ss A').format('hh:mm:ss A');
  }
dsi
  • 2,817
  • 12
  • 48
  • 94
  • This should help: https://stackoverflow.com/questions/14638018/current-time-formatting-with-javascript – Kinglish May 13 '21 at 14:33
  • Its using new Date() function. I just do have string for time values which can be 1 digit or 2 digits as above description. If there is no any existing function then, might need to do string operation. – dsi May 13 '21 at 14:55

1 Answers1

0

Hopefully this will help convert any time-like string to the format you want.

function getTimeFormat(time) {
let ta = time.trim().split(" ");
let slots = ta[0].split(":");
while(slots.length<3) slots.push(""); // make sure we have h:m:s slots
return slots.map( n => n.padStart(2, '0')).join(":") + " " + (ta.length>1 ? ta[1].trim().toUpperCase() : "");
}
console.log(getTimeFormat('3 pm'));  
console.log(getTimeFormat('3:1 pm'));  
console.log(getTimeFormat('3:15 pm'));  
Kinglish
  • 21,356
  • 3
  • 21
  • 41