当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。
其他回答
function monthFormated(date) {
//If date is not passed, get current date
if(!date)
date = new Date();
month = date.getMonth();
// if month 2 digits (9+1 = 10) don't add 0 in front
return month < 9 ? "0" + (month+1) : month+1;
}
如果你想要一个像"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', ' ');
date-fns。
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
这里的答案很有帮助,但我需要的不仅仅是一个默认名称:月、日、月、小时和秒。
有趣的是,虽然以上都需要“0”的前缀,但只有month需要“+ 1”,其他都不需要。
为例:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。