当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
只是另一个例子,几乎是一行。
var date = new date (); console.log((date.getMonth() < 9 ?'0': ")+ (date.getMonth()+1));
其他回答
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
我想做这样的事情,这就是我所做的
附注:我知道上面有正确答案,但我只是想在这里补充一些我自己的东西
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;
}
例如month:
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
}
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
date-fns。
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');