Tutorial :Get month in mm format in javascript



Question:

How do I retrieve the month from the current date in mm format? (i.e. "05")

This is my current code:

var currentDate = new Date();  var currentMonth = currentDate.getMonth() + 1;  


Solution:1

if (currentMonth < 10) { currentMonth = '0' + currentMonth; }  


Solution:2

An alternative way:

var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2)  


Solution:3

One line solution:

var currentMonth = (currentDate.getMonth() < 10 ? '0' : '') + currentDate.getMonth();  


Solution:4

for the date:

("0" + this.getDate()).slice(-2)  

and similar for the month:

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


Solution:5

In order for the accepted answer to return a string consistently, it should be:

if(currentMonth < 10) {      currentMonth = '0' + currentMonth;  } else {      currentMonth = '' + currentMonth;  }  

Or:

currentMonth = (currentMonth < 10 ? '0' : '') + currentMonth;  

Just for funsies, here's a version without a conditional:

currentMonth = ('0' + currentMonth).slice(-2);  

Edit: switched to slice, per Gert G's answer, credit where credit is due; substr works too, I didn't realize it accepts a negative start argument


Solution:6

If you do this

var currentDate = new Date();  var currentMonth = currentDate.getMonth() + 1;  

then currentMonth is a number, which you can format as you want, see this question that will help you with formatting: How can I format an integer to a specific length in javascript?


Solution:7

var CurrentDate = new Date();      CurrentDate.setMonth(CurrentDate.getMonth());        var day = CurrentDate.getDate();      var monthIndex = CurrentDate.getMonth()+1;      if(monthIndex<10){          monthIndex=('0'+monthIndex);      }      var year = CurrentDate.getFullYear();        alert(monthIndex);  


Solution:8

ES6 version inpired by @gert-grenander

let date = new Date();  let month = date.getMonth() +1;  month = (`0${month}`).slice(-2);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »