如何仅使用 date-fns 格式化时间

How to format time only using date-fns

使用date-fns,如何在使用date-fns 的代码段下方进行转换。 基本上,输入类似于“01:40:20 PM”或“1:4:2 PM”或“3:2 PM”或“03:2 PM” 并且预期输出是一致的,例如,'03:02:00 PM',格式为 hh:mm:ss。

我找不到任何只允许格式化时间的特定方法。

使用moment js,效果如下:

 if (moment(timeString, ['h:m:s A', 'h:m A'], true).isValid()) {
    return moment(timeString, 'hh:mm:ss A').format('hh:mm:ss A');
  }

希望这有助于将任何类似时间的字符串转换为您想要的格式。

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