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?
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?
- 1 Isn't that like a one-line function to write? Although there's an sprintf for JavaScript. – Dave Newton Commented Jun 2, 2012 at 17:06
- I get sprintf is not defined. Is this supported on all browsers? – Tim Tom Commented Jun 2, 2012 at 17:09
- 1 @TimTom it's not in browsers but custom code that you have to include, hence the link to the project – Esailija Commented Jun 2, 2012 at 17:10
-
1
There's no built-in
sprintf
function, that page is about a custom implementation which you need to download and include yourself. In my opinion, it's overkill if you only need this to pad a number with zeroes. – Mattias Buelens Commented Jun 2, 2012 at 17:10 - @MattiasBuelens +1 for overkill... but it didn't seem like the OP was really attempting to apply themselves, so I figured what the heck. – Dave Newton Commented Jun 2, 2012 at 17:12
4 Answers
Reset to default 10You can do it like this...
mth = ("0" + mth).slice(-2);
Also, keep in mind that months are 0
based, so you may want this...
mth = ("0" + ++mth).slice(-2);
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()
You might want to look at a sprintf library for Javascript, if you're looking for more robust functionality than a simple zero-padding function.
http://www.diveintojavascript./projects/javascript-sprintf
Underscore.string has an implementation as well.
https://github./edtsech/underscore.string
let number = 7;
let paddedNumber = number.toString().padStart(2, '0');
console.log(paddedNumber);
output:- 07
If the original string is already longer than the specified length, no padding is added
let number = 70;
let paddedNumber = number.toString().padStart(2, '0');
console.log(paddedNumber);
output:- 70