javascriptdatetimemomentjsdate-fns

How to format time only using date-fns


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

Solution

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