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

如何使用JavaScript生成无逗号的月/日 时:分 上/下午日期格式?

实现指定格式的日期输出

你可以通过配置toLocaleString的选项参数,精准控制日期时间的展示格式:

const currentDate = new Date();
const formattedDate = currentDate.toLocaleString('en-US', {
  month: 'numeric',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
});
console.log(formattedDate);
// 输出示例: 9/22 8:03 PM

参数说明:

  • month: 'numeric':以数字形式展示月份(如9而非September)
  • day: 'numeric':以数字形式展示日期
  • hour: 'numeric':配合hour12: true启用12小时制显示小时
  • minute: 'numeric':显示分钟数
  • hour12: true:开启上/下午(AM/PM)标识

也可以拆分日期和时间的格式化逻辑后拼接,效果完全一致:

const currentDate = new Date();
const datePart = currentDate.toLocaleDateString('en-US', { month: 'numeric', day: 'numeric' });
const timePart = currentDate.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
const formattedDate = `${datePart} ${timePart}`;
console.log(formattedDate);

以上两种方式都能直接生成你需要的「月/日 时:分 上/下午」格式,自动剔除年份和逗号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:05:21