当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:

对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?


当前回答

例如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
}

其他回答

("0" + this.getDate()).slice(-2)

对于日期,类似的:

("0" + (this.getMonth() + 1)).slice(-2)

这个月。

这就是我的解决方案:

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 ?

哪里有亭子

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。

更现代的方法可能是使用"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}`

我会这样做:

var date = new date (2000,0,9); var str = new Intl。DateTimeFormat(“en - us”{ 月:“便是”, 天:“便是”, 年:“数字” }) .format(日期); console.log (str);//打印“01/09/2000”