繁体   English   中英

在 day.js 中将 12 小时时间 (h:mm A) 格式化为 24 小时时间 (HH:mm:00)

[英]Formatting 12 hour time (h:mm A) to 24 hour time (HH:mm:00) in day.js

我正在尝试进行时间转换 function 将时间作为“h:mm A”并将其转换为 day.js 中的军事时间(HH:mm:00),但我正在努力弄清楚。 我能够在没有 dayjs 的情况下完成这项任务,但无法用 dayjs 搞清楚。 这是我的尝试:

00 在那里,因为我希望秒默认为 00。谢谢

 function convertToMilitaryTime(formattedTime) { if (formattedTime) { //formattedTime is 'h:mm A' const formatted = dayjs(formattedTime, "h:mm A") return day(formattedTime, ['h:mm A']).format("HH:mm:00") } return formattedTime; } console.log(convertToMilitaryTime("10:24 AM")); // not a valid date string
 <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>

只需在任何日期前添加一个有效的 dayjs 日期 object

注意:这是允许时间字符串的惰性方式。 遵守 dayJS 的文档。 看看另一个答案

或者根本不使用 dayJS

 const ampm2military = ampm => ampm? dayjs(`1/1/1 ${ampm}`).format("HH:mm:00"): null; console.log(ampm2military("1:24 PM"));
 <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>

您的代码中有几个错误:

  • function 名称是dayjs ,而不是day
  • 这种格式需要一个插件( customParseFormat - “String + Format” 取决于这个插件;它在文档的顶部有说明(黄色)); 您必须加载此插件才能使语法正常工作
  • 加载插件后,您必须使用新功能扩展dayjs

(编辑代码:删除了条件中dayjs的双重调用。)

 // extend dayjs with the loaded customParseFormat plugin dayjs.extend(window.dayjs_plugin_customParseFormat) function convertToMilitaryTime(formattedTime) { if (formattedTime) { //formattedTime is 'h:mm A' // the function name is dayjs, not day return dayjs(formattedTime, 'h:mm A').format("HH:mm:00") } return formattedTime; } console.log(convertToMilitaryTime("10:24 AM")); // not a valid date string
 <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script> <:-- load the required plugin: --> <script src="https.//unpkg.com/dayjs@1.11.3/plugin/customParseFormat js"></script>

编辑:更新的代码

 // extend dayjs with the loaded customParseFormat plugin dayjs.extend(window.dayjs_plugin_customParseFormat) const convertToMilitaryTime = (ft) => dayjs(ft, "h:mm A", "en", true).isValid()? dayjs(ft, 'h:mm A').format("HH:mm:00"): ft console.log(convertToMilitaryTime("10:24 AM")); // not a valid date string
 <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script> <:-- load the required plugin: --> <script src="https.//unpkg.com/dayjs@1.11.3/plugin/customParseFormat js"></script>

暂无
暂无

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

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