当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
date-fns。
import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');
其他回答
如果你想getDate()函数返回日期为01而不是1,这里是它的代码.... 让我们假设今天的日期是2018年01月11日
var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();
console.log(today); //Output: 2018-11-1
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today); //Output: 2018-11-01
为什么不用padStart ?
哪里有亭子
targetLength为2 padString为0
//来源:https://stackoverflow.com/a/50769505/2965993 var dt= new date(); year=dt.getfullyear(); month=(dt.getmonth()+1).tostring()。padStart(2,“0”); date().tostring()。padStart(2,“0”); log(year+'/'+ month+'/'+ day);
这将总是返回2位数字,即使月或日小于10。
注:
这将只适用于Internet Explorer,如果js代码是转译使用babel。 getFullYear()返回4位年份,不需要padStart。 getMonth()返回从0到11的月份。 在填充前将1添加到月份,以保持1到12。 getDate()返回从1到31的日期。 第7天将返回07,因此我们不需要在填充字符串之前添加1。
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。
例如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
}