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

React项目中使用date-fns格式化时间为24小时制的实现方法

date-fns 24小时制时间格式化解决方案

问题出在格式化占位符选择错误,date-fns 中hh是12小时制的小时占位符,要输出24小时制的时间,替换为大写的HH即可。

修改后的代码如下:

const sampleText = 'Tue Aug 03 2021 18:49:11 GMT+0800';
const sampleDate = new Date(sampleText);
format(sampleDate, 'HH:mm')

补充几个常用小时占位符的区别,避免后续踩坑:

  • h:12小时制,无前导零,例如下午6点会输出为6
  • hh:12小时制,有前导零,例如下午6点会输出为06
  • H:24小时制,无前导零,例如上午9点会输出为9
  • HH:24小时制,有前导零,例如上午9点会输出为09

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:15:05