当我们在date
对象上调用getMonth()
和getDate()
时,我们将得到single digit number
。例如:
对于january
,它显示1
,但我需要将其显示为01
。

("0" + this.getDate()).slice(-2)
对于日期,以及类似的:
("0" + (this.getMonth() + 1)).slice(-2)
月。

如果你想要像“YYYY-MM-DDTHH:mm:ss”这样的格式,那么这可能会更快:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
或者常用的 MySQL 日期时间格式“YYYY-MM-DD HH:mm:ss”:
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
我希望这有帮助

为什么不使用padStart
?
padStart(targetLength,padString)
where
targetLength
is2
padString
is0
// Source: https://stackoverflow.com/a/50769505/2965993
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
这将始终返回 2 位数字,即使月或日小于 10。
笔记:
如果 js 代码使用babel进行 transpiled,这将仅适用于 Internet Explorer。
getFullYear()
返回 4 位数年份,不需要padStart
。
getMonth()
返回从 0 到 11 的月份。
1 添加到填充之前的月份,以保持 1 到 12。
getDate()
返回从 1 到 31 的日期。
第 7 天将返回07
,因此我们不需要在填充字符串之前添加 1。
月份示例:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
您还可以使用以下函数扩展Date
对象:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(31条)