当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
我想做这样的事情,这就是我所做的
附注:我知道上面有正确答案,但我只是想在这里补充一些我自己的东西
const todayIs = async () =>{
const now = new Date();
var today = now.getFullYear()+'-';
if(now.getMonth() < 10)
today += '0'+now.getMonth()+'-';
else
today += now.getMonth()+'-';
if(now.getDay() < 10)
today += '0'+now.getDay();
else
today += now.getDay();
return today;
}
其他回答
只是另一个例子,几乎是一行。
var date = new date (); console.log((date.getMonth() < 9 ?'0': ")+ (date.getMonth()+1));
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;
}
更现代的方法可能是使用"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}`
如果你能给我点时间的话我想问的是
YYYYMMDD
为了今天,和大家相处:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
date-fns。
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');