3

I have two function to get a date format. The different is dd-mm-yyyy and yyyy-mm-dd format. Currently the 1st function style is 12-3-2020. So how to make the month is including 0 just like this 12-03-2020 and 2nd style to be as 2020-03-13.

Below are the functions.

function displayDate(input_date){

    proc_date = new Date(input_date)
    year = proc_date.getYear() + 1900
    month = proc_date.getMonth() + 1
    day = proc_date.getDate()

    return day +"-"+ month +"-"+ year;
}

function sendDate(input_date){

    proc_date = new Date(input_date)
    year = proc_date.getYear() + 1900
    month = proc_date.getMonth() + 1
    day = proc_date.getDate()

    return year +"-"+ month +"-"+ day;
}
Udhay Titus
  • 5,761
  • 4
  • 23
  • 41
mastersuse
  • 936
  • 1
  • 15
  • 35
  • Do not use [*getYear*](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear), use [*getFullYear*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear). You should declare variables to keep them local to their enclosing context. – RobG Mar 31 '20 at 11:45

2 Answers2

2

add if condition for month and day it will work's

function displayDate(input_date){

    proc_date = new Date(input_date)
    year = proc_date.getYear() + 1900
    month = proc_date.getMonth() + 1
    day = proc_date.getDate()
    
    if(month < 10)
    {
      month = "0" + month;
    }
    if(day < 10)
    {
      day = "0" + day;
    }
    console.log(day +"-"+ month +"-"+ year);
    return day +"-"+ month +"-"+ year;
}
displayDate("12-3-2020");

function sendDate(input_date){

    proc_date = new Date(input_date)
    year = proc_date.getYear() + 1900
    month = proc_date.getMonth() + 1
    day = proc_date.getDate();
    
    if(month < 10)
    {
      month = "0" + month;
    }
    if(day < 10)
    {
      day = "0" + day;
    }

    console.log(year +"-"+ month +"-"+ day);
    return year +"-"+ month +"-"+ day;
}

sendDate("12-3-2020");
Udhay Titus
  • 5,761
  • 4
  • 23
  • 41
1

You need to pad your month (and day) with 0:

alert(pad(3));
alert(pad(12));

function pad(num) {
  return ('0' + num).substr(-2);
}
Justinas
  • 41,402
  • 5
  • 66
  • 96