How do I format 7 as '07' in string in JavaScript?

javascript, jquery

Solution

var newmonth = month < 10 ? '0' + month : month; // if month is number
                                                 // else use parseInt(month, 10)

You can also make a function for general use:

function formatting(target) {
  return target < 10 ? '0' + target : target;
}

You can use above approach for month and days.

and to get a 4 digits year you can use `.getFullYear()`

Problem

I have JavaScript day, month and year. I need my day to be in 2 digits, my months also to be in 2 digits and year in 4 digits. Eg. If month is `7` it should give me string as `'07'`. If it is `12` then it should return `'12'`. I google for it but I only found `toFixed` and `toPrecision`, both of which have different functions. How do I format it?

Original source