当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:

对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?


当前回答

我的解决方案:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

用法:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http://jsfiddle.net/8xy4Q/1/

其他回答

我会这样做:

var date = new date (2000,0,9); var str = new Intl。DateTimeFormat(“en - us”{ 月:“便是”, 天:“便是”, 年:“数字” }) .format(日期); console.log (str);//打印“01/09/2000”

更现代的方法可能是使用"padStart"

const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();

然后,如果你愿意,你可以构建一个模板字符串:

`${day}/${month}/${year}`

date-fns。

import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
("0" + this.getDate()).slice(-2)

对于日期,类似的:

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

这个月。

$("body").delegate("select[name='package_title']", "change", function() {

    var price = $(this).find(':selected').attr('data-price');
    var dadaday = $(this).find(':selected').attr('data-days');
    var today = new Date();
    var endDate = new Date();
    endDate.setDate(today.getDate()+parseInt(dadaday));
    var day = ("0" + endDate.getDate()).slice(-2)
    var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
    var year = endDate.getFullYear();

    var someFormattedDate = year+'-'+month+'-'+day;

    $('#price_id').val(price);
    $('#date_id').val(someFormattedDate);
});