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

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


当前回答

我建议您使用另一个名为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项是正确答案

其他回答

以下命令用于转换db2日期格式 即YYYY-MM-DD使用三元运算符

var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);  
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate; 
alert(createdDateTo);
("0" + this.getDate()).slice(-2)

对于日期,类似的:

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

这个月。

如果你能给我点时间的话我想问的是

YYYYMMDD

为了今天,和大家相处:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');

date-fns。

import { lightFormat } from 'date-fns';
lightFormat(new Date(), 'dd');

使用Moment.js可以这样做:

moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month