当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
其他回答
最好的方法是创建自己的简单格式化器(如下所示):
getDate()返回每月的日期(从1-31) getMonth()返回月份(从0到11)<从零开始,0=一月,11=十二月 getFullYear()返回年份(4位数字)<不要使用getYear()
function formatDateToString(date){
// 01, 02, 03, ... 29, 30, 31
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
// 01, 02, 03, ... 10, 11, 12
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
// 1970, 1971, ... 2015, 2016, ...
var yyyy = date.getFullYear();
// create the format you want
return (dd + "-" + MM + "-" + yyyy);
}
另外一个版本在这里https://jsfiddle.net/ivos/zcLxo8oy/1/,希望对大家有用。
var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup
strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
$("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);
});
new Date().getMonth()方法以数字形式返回月份(0-11)
用这个函数你可以很容易地得到正确的月份数。
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。