You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用day.js将h:mm A格式12小时制时间转换为HH:mm:00格式24小时制时间

问题根因

代码运行报错、转换失败来自两个核心问题:

  • dayjs核心包默认仅支持解析ISO 8601标准格式的时间字符串,h:mm A属于自定义格式,必须加载CustomParseFormat插件才能被正确识别解析,否则会判定输入为无效日期。
  • 代码中存在拼写错误,解析逻辑里调用了未定义的day()方法,和全局挂载的dayjs方法名不一致。
修复实现
  1. 引入CustomParseFormat插件并完成注册,开启自定义格式解析能力
  2. 修正方法名拼写错误,解析时明确传入输入对应的格式规则,最终按要求格式输出即可
完整代码

脚本引入(CDN场景)

<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/plugin/customParseFormat.js"></script>

转换逻辑

// 注册自定义解析插件
dayjs.extend(dayjs_plugin_customParseFormat);

function convertToMilitaryTime(formattedTime) {
  if (formattedTime) {
    // 按h:mm A格式解析输入,输出固定秒数为00的24小时制时间
    return dayjs(formattedTime, "h:mm A").format("HH:mm:00")
  }
  return formattedTime;
}

// 测试用例
console.log(convertToMilitaryTime("10:24 AM")); // 输出 10:24:00
console.log(convertToMilitaryTime("1:30 PM")); // 输出 13:30:00
console.log(convertToMilitaryTime("12:10 AM")); // 输出 00:10:00

如果是npm模块化场景,只需先通过import customParseFormat from 'dayjs/plugin/customParseFormat'引入插件,再执行dayjs.extend(customParseFormat)注册即可,其余转换逻辑完全相同。

内容的提问来源于stack exchange,提问作者karjeezy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 23:18:20