当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
这里的答案很有帮助,但我需要的不仅仅是一个默认名称:月、日、月、小时和秒。
有趣的是,虽然以上都需要“0”的前缀,但只有month需要“+ 1”,其他都不需要。
为例:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
其他回答
我建议您使用另一个名为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项是正确答案
这里的答案很有帮助,但我需要的不仅仅是一个默认名称:月、日、月、小时和秒。
有趣的是,虽然以上都需要“0”的前缀,但只有month需要“+ 1”,其他都不需要。
为例:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
("0" + this.getDate()).slice(-2)
对于日期,类似的:
("0" + (this.getMonth() + 1)).slice(-2)
这个月。
只是另一个例子,几乎是一行。
var date = new date (); console.log((date.getMonth() < 9 ?'0': ")+ (date.getMonth()+1));
这就是我的解决方案:
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;