当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
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;
}
其他回答
如果你检查的是小于10的,你不需要为它创建一个新函数。只需将变量赋值到括号中,并返回一个三元操作符。
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
如果你想要一个像"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', ' ');
使用Moment.js可以这样做:
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
这就是我的解决方案:
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;
更现代的方法可能是使用"padStart"
const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();
然后,如果你愿意,你可以构建一个模板字符串:
`${day}/${month}/${year}`