简体   繁体   English

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

[英]How to format time only using date-fns

Using date-fns, how it could be converted below piece of code using date-fns.使用 date-fns,如何使用 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.基本上,输入类似于“01:40:20 PM”或“1:4:2 PM”或“3:2 PM”或“03:2 PM”,并且预计output将保持一致,例如“03:02: 00 PM',采用 hh:mm:ss 格式。

I could not find any particular method that allows format with time only.我找不到任何只允许使用时间格式的特定方法。

Using moment js, it works fine as below:使用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');
  }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM