当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
我会这样做:
var date = new date (2000,0,9); var str = new Intl。DateTimeFormat(“en - us”{ 月:“便是”, 天:“便是”, 年:“数字” }) .format(日期); console.log (str);//打印“01/09/2000”
其他回答
new Date().getMonth()方法以数字形式返回月份(0-11)
用这个函数你可以很容易地得到正确的月份数。
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
这里的答案很有帮助,但我需要的不仅仅是一个默认名称:月、日、月、小时和秒。
有趣的是,虽然以上都需要“0”的前缀,但只有month需要“+ 1”,其他都不需要。
为例:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
来自MDN的建议:
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
http://jsfiddle.net/v4qcf5x6/
不是一个答案,但这里是我如何得到我在一个变量中需要的日期格式
function setDateZero(date){
return date < 10 ? '0' + date : date;
}
var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);
希望这能有所帮助!
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}