在javascript中以mm格式获取月份

Mic*_*ern 17 javascript date

如何从mm格式的当前日期检索月份?(即"05")

这是我目前的代码:

var currentDate = new Date();
var currentMonth = currentDate.getMonth() + 1;
Run Code Online (Sandbox Code Playgroud)

Ger*_*der 53

另一种方式:

var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2)
Run Code Online (Sandbox Code Playgroud)

  • +1是因为我复制了你,作为部分答案。 (2认同)

Mat*_*att 21

if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
Run Code Online (Sandbox Code Playgroud)

  • 你想要 `&lt;10` 否则 9 不会返回 '09' (2认同)

小智 5

一线解决方案:

var currentMonth = (currentDate.getMonth() < 10 ? '0' : '') + currentDate.getMonth();
Run Code Online (Sandbox Code Playgroud)