【问题标题】:How to format time only using date-fns如何仅使用 date-fns 格式化时间
【发布时间】:2021-08-03 20:13:55
【问题描述】:

使用 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 A 格式。

我找不到任何允许仅使用时间格式的特定方法。

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

【问题讨论】:

  • 这应该会有所帮助:stackoverflow.com/questions/14638018/…
  • 它使用新的 Date() 函数。我只是有时间值的字符串,可以是 1 位或 2 位,如上所述。如果没有任何现有函数,则可能需要进行字符串操作。

标签: javascript date time momentjs date-fns


【解决方案1】:

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

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

【讨论】:

  • 谢谢。似乎它在 date-fns 实用程序中并不直接。
猜你喜欢
  • 2020-10-19
  • 2021-01-29
  • 2021-11-14
  • 2018-07-24
  • 2021-01-23
  • 2021-11-27
  • 2018-01-22
  • 2021-03-26
  • 2020-06-15
相关资源
最近更新 更多