javascript 如何将前导“0”添加到日期字符串的月/日?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14915718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:54:13  来源:igfitidea点击:

How to add leading "0" to month/day of date string?

javascriptjquerydatedatepicker

提问by user2079233

so i wrote up a method that takes a number and subtracts the amount of months from the current date.

所以我写了一个方法,它需要一个数字并从当前日期中减去月数。

I am trying to figure out how can i add a '0' in front of the months that are less that 10. Also, how can I add a '0' in front on the days that are less than ten as well.

我想弄清楚如何在小于 10 的月份前添加“0”。此外,如何在小于 10 的天数前添加“0”。

Currently, when it returns the object (2012-6-9). It returns 6 and 9 with no '0' in front of it, can someone show me how to do it?

当前,当它返回对象时 (2012-6-9)。它返回 6 和 9,前面没有“0”,有人可以告诉我怎么做吗?

Here is my code

这是我的代码

lastNmonths = function(n) {
    var date = new Date();

    if (n <= 0)
        return [date.getFullYear(), date.getMonth() + 1 , date.getDate()].join('-');
    var years = Math.floor(n/12); 


   var months = n % 12;


    if (years > 0)
        date.setFullYear(date.getFullYear() - years);

    if (months > 0) {
        if (months >= date.getMonth()) {
            date.setFullYear(date.getFullYear()-1 );
            months = 12 - months; 
            date.setMonth(date.getMonth() + months );
        } else {
            date.setMonth(date.getMonth() - months);
        }
    }

}

    return [date.getFullYear(), date.getMonth() + 1, date.getDate()].join('-');
};

回答by Arnaud Christ

You can also avoid testing if n < 10 by using :

如果 n < 10,您还可以使用以下方法避免测试:

("0" + (yourDate.getMonth() + 1)).slice(-2)

回答by srosh

you can write a little function like this :

你可以写一个这样的小函数:

function pad(n) {return (n<10 ? '0'+n : n);}

and pass month and day to it

并将月份和日期传递给它

return [date.getFullYear(),pad(date.getMonth() + 1), pad(date.getDate())].join('-');

回答by imalvinz

Try concat the "0":

尝试连接“0”:

   month = date.getMonth() + 1 < 10 ? '0' + date.getMonth() + 1 : date.getMonth() + 1
   return [date.getFullYear(), month, date.getDate()].join('-');