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
  • 3,199
  • 12
  • 59
  • 102
  • 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

2 Answers2

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
  • 23,358
  • 3
  • 22
  • 43
0

This worked for me from: "17:00:00.000" to "05:00 PM"

import { format, parse } from "date-fns";

...

const time = '17:00:00.000';

...

{format(parse(time.split(":", 2).join(":"), "HH:mm", new Date()), "hh:mm a")}
atazmin
  • 4,757
  • 1
  • 32
  • 23