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

如何为年/月/日格式日期中小于10的月份和日期添加前置0

你只需要对拆分出来的月份、日期做补零处理即可,字符串自带的padStart方法可以非常方便的实现这个需求,它会在字符串长度不足指定值时,在开头填充指定字符直到达到目标长度,刚好适配小于10的月份/日期补前置0的需求。修改后的代码如下:

let date = '2021/1/31';

const addZeros = (date) => {
  // 一次拆分得到年月日,避免重复调用split
  const [year, month, day] = date.split('/');
  // 对月、日做2位补零处理
  const formatMonth = month.padStart(2, '0');
  const formatDay = day.padStart(2, '0');
  // 按你需要的斜杠分隔格式返回结果
  return `${year}/${formatMonth}/${formatDay}`;
};

console.log(addZeros(date)); // 输出:2021/01/31

测试用例运行结果完全匹配要求:

  • 输入2021/9/14 → 输出2021/09/14
  • 输入2021/1/7 → 输出2021/01/07
  • 输入2021/10/17 → 输出2021/10/17

如果需要兼容不支持padStart的老旧运行环境,可以改用条件判断的写法:

const addZeros = (date) => {
  const [year, month, day] = date.split('/');
  const formatMonth = Number(month) < 10 ? `0${month}` : month;
  const formatDay = Number(day) < 10 ? `0${day}` : day;
  return `${year}/${formatMonth}/${formatDay}`;
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:57:05