当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
new Date().getMonth()方法以数字形式返回月份(0-11)
用这个函数你可以很容易地得到正确的月份数。
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
其他回答
为什么不用padStart ?
哪里有亭子
targetLength为2 padString为0
//来源:https://stackoverflow.com/a/50769505/2965993 var dt= new date(); year=dt.getfullyear(); month=(dt.getmonth()+1).tostring()。padStart(2,“0”); date().tostring()。padStart(2,“0”); log(year+'/'+ month+'/'+ day);
这将总是返回2位数字,即使月或日小于10。
注:
这将只适用于Internet Explorer,如果js代码是转译使用babel。 getFullYear()返回4位年份,不需要padStart。 getMonth()返回从0到11的月份。 在填充前将1添加到月份,以保持1到12。 getDate()返回从1到31的日期。 第7天将返回07,因此我们不需要在填充字符串之前添加1。
这就是我的解决方案:
function leadingZero(value) {
if (value < 10) {
return "0" + value.toString();
}
return value.toString();
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + 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")
currentDate(){
var today = new Date();
var dateTime = today.getFullYear()+'-'+
((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
(today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
(today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
(today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
(today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());
return dateTime;
},
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}