获取当前时间展示为05-08的形式,只有月日如果只有一位数就补0,优化?

获取当前时间展示为05-08的形式,只有月日如果只有一位数就补0,两位正常显示,这是现在的写法,可不可以优化一下我觉得现在写的比较麻烦?

    const myDate = new Date();
    const today = myDate.toLocaleDateString().split('/').join('-');
    let times = today.split('-');
    const Year = times[0];
    const Month = times[1];
    const Day = times[2];
    let mounth='';
    if(Month.length===1){
       mounth='0'+Month
    }else{
       mounth=Month
    }
    let day='';
    if(Day.length===1){
       day='0'+Day
    }else{
       ay=Day
    }
    const Newtoday=mounth+'-'+day;
阅读 2.5k
3 个回答
const getMonthDay = (str = '-') => {
   const arr = new Date().toLocaleDateString().match(/\d+/g).slice(1)
   return arr.map(e => e.padStart(2, 0)).join(str)
}
const myDate = new Date();
var Day = myDate.getDate() > 9 ? myDate.getDate().toString() : '0' + myDate.getDate();
var Month = myDate.getMonth() + 1 > 9 ? (myDate.getMonth() + 1).toString() : '0' + (myDate.getMonth() + 1);
const Newtoday = Month + '-' + Day;

最好封装成公共函数,重复利用;

moment

moment().format("YYYY-MM-DD")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题