Home > front end >  Get Current Date using JS
Get Current Date using JS

Time:01-10

I'm trying to get the current date so I can use it at the ending of this link. My code is almost correct but can't figure out what is going wrong.

My results are almost correct but the code returns with the following date 01/0/2022 instead of 01/09/2022

Can someone help me figure out this small bug?

<script>
    const getDate = () => {
        let newDate = new Date();
        let year = newDate.getFullYear();
        let month = newDate.getMonth()   1;
        let d = newDate.getDay();
        return month   '/'   d   '/'   year;
    }



    document.getElementById('Ao').src =
        'http://zumdb-prod.itg.com/zum/AppServlet?action=aotool&jspURL=clusterTools/toolset.jsp&fegoaltype=RAW&eedbListName=ZUM_CMP_DNS_CMP_Clean&facility=DMOS5-CLUSTER&monthDate='
        .concat(getDate());

    document.getElementById('MTD').src =
        'http://zumdb-prod.itg.com/zum/AppServlet?action=aotoolFe&jspURL=clusterTools/toolsetFe.jsp&fegoaltype=RAW&eedbListName=ZUM_DIFF_TEL_IPD_HTO&facility=DMOS5-CLUSTER&monthDate='
        .concat(getDate());
</script>

CodePudding user response:

You should be using getDate() and not getDay(). The latter returns the zero-based day of the week (starting Sunday). You want to get the date of the month.

In order to ensure you get double digits for the month and day, you need to convert those numbers to string first, and then use String.prototype.padStart.

const getDate = () => {
  const newDate = new Date();
  const year = newDate.getFullYear();
  const month = newDate.getMonth()   1;
  const d = newDate.getDate();
  
  return `${month.toString().padStart(2, '0')}/${d.toString().padStart(2, '0')}/${year}`;
}

console.log(getDate());

CodePudding user response:

Here are alternative methods for native date formatting using toLocaleString()

m/d/yyyy

const getDate = () => {
  const date = new Date();
  return date.toLocaleString().split(",")[0];
}

console.log(getDate());

mm/dd/yyyy

const getDate = () => {
  const date = new Date();
  return date.toLocaleString('en-US', {
    month: '2-digit',
    day: '2-digit',
    year: 'numeric'
  });
}

console.log(getDate());

  •  Tags:  
  • Related