如何在JavaScript日期中创建完整的月份?

3

我有两个函数可以获取日期格式,区别在于dd-mm-yyyyyyyy-mm-dd格式。目前第一个函数的样式是12-3-2020。那么如何让月份包含0,像这样:12-03-2020,并将第二种样式设为2020-03-13

以下是这两个函数:

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;
}

不要使用[getYear](https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear),请使用[*getFullYear*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear)。您应该声明变量以使它们局限于其封闭上下文。 - RobG
2个回答

2

在月份和日期上添加条件,它将起作用。

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");


1
谢谢,If else条件解决了第一个函数的问题。 - mastersuse

1
您需要在月份(和日期)前补0:

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

function pad(num) {
  return ('0' + num).substr(-2);
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接