In general, the javascript Date() object returns the current day date-time object. But when we need to get a formatted date from the Date() object,  we have to write some extra code. Hence we need a formatted date in javascript, I will write a function for reuse.


  • Get current date using new Date() object.
  • Get a date, month, and year from the Date() object.
  • Store date, month, and year into an array.
  • Return date formate we need.

Example Code:

function getCurrentDate(formate='mm/dd/yyyy'){
    var today = new Date();
    var currentDate = {};
    currentDate['dd'] = String(today.getDate()).padStart(2, '0');
    currentDate['mm'] = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    currentDate['yyyy'] = today.getFullYear();

    today = formate.replace("mm", currentDate['mm']);
    today = today.replace("dd", currentDate['dd']);
    today = today.replace("yyyy", currentDate['yyyy']);

    return today;
}


Example Outputs:


console.log(getCurrentDate());

08/20/2021


console.log(getCurrentDate('dd/mm/yyyy'));

20/08/2021


console.log(getCurrentDate('dd-mm-yyyy'));

20-08-2021


console.log(getCurrentDate('mm-dd-yyyy'));

08-20-2021


console.log(getCurrentDate('mm-yyyy'));

08-2021