当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
其他回答
为什么不用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。
如果你能给我点时间的话我想问的是
YYYYMMDD
为了今天,和大家相处:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
怎么容易?
new Date().toLocaleString("en-US", { day: "2-digit" })
其他选项是可用的:
工作日 一年 月
更多信息请点击这里。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。
来自MDN的建议:
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
http://jsfiddle.net/v4qcf5x6/