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

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


当前回答

三元运算符解

如果月份或日期小于10,则简单的三元运算符可以在数字之前添加“0”(假设需要在字符串中使用此信息)。

let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();

其他回答

不是一个答案,但这里是我如何得到我在一个变量中需要的日期格式

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);

希望这能有所帮助!

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

另外一个版本在这里https://jsfiddle.net/ivos/zcLxo8oy/1/,希望对大家有用。

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")

new Date().getMonth()方法以数字形式返回月份(0-11)

用这个函数你可以很容易地得到正确的月份数。

function monthFormatted() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

我建议您使用另一个名为Moment https://momentjs.com/的库

这样你就可以直接格式化日期,而不需要做额外的工作

const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'

确保你也导入了moment,以便能够使用它。

yarn add moment 
# to add the dependency
import moment from 'moment' 
// import this at the top of the file you want to use it in

D项是正确答案