undefinedfix
Sign in

The current time is displayed in the form of 05-08. If there is only one digit in the month and day, 0 will be filled. Optimize?

pyktz edited in Sat, 13 Aug 2022

Get the current time and display it in the form of 05-08, only month and day. If there is only one digit, fill in 0, and two digits display normally. This is the current writing method. Can you optimize it? I think it's troublesome to write it now?

    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;
3 Replies
tedtu
commented on Sat, 13 Aug 2022
const getMonthDay = (str = '-') => {
   const arr = new Date().toLocaleDateString().match(/\d+/g).slice(1)
   return arr.map(e => e.padStart(2, 0)).join(str)
}
ePumps
commented on Sat, 13 Aug 2022
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;

It is better to encapsulate it as a common function and reuse it;

luprchal
commented on Sat, 13 Aug 2022

moment

moment().format("YYYY-MM-DD")
lock This question has been locked and the reply function has been disabled.