猿问

如何获取2位数格式的JavaScript的月份和日期?

当调用getMonth()getDate()on date对象时,我们将获得single digit number。例如 :

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


三国纷争
浏览 1153回答 3
3回答

撒科打诨

("0" + this.getDate()).slice(-2)日期,类似:("0" + (this.getMonth() + 1)).slice(-2)

精慕HU

本月的示例:function getMonth(date) {&nbsp; var month = date.getMonth() + 1;&nbsp; return month < 10 ? '0' + month : '' + month; // ('' + month) for string result}&nbsp;&nbsp;您还可以Date使用以下功能扩展对象:Date.prototype.getMonthFormatted = function() {&nbsp; var month = this.getMonth() + 1;&nbsp; return month < 10 ? '0' + month : '' + month; // ('' + month) for string result}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答