Reputation: 11377
I have a date string that is created by adding the following pieces:
var dateString = d + "/" + m + "/" + y;
The other variables are created previously in my code as being fetched from an internal web page (d = day, m = month, y = year). This works fine so far.
How can I achieve that a leading zero is added to them if d and/or m consist of only digit ? E.g. if d = 1 then it should become 01 and the same for m.
Many thanks in advance for any help with this, Tim.
Upvotes: 0
Views: 2123
Reputation: 89
Try following
var d_str = ("00" + d).slice(-2);
var m_str = ("00" + m).slice(-2);
var dateString_formatted = d_str + "/" + m_str + "/" + y;
Upvotes: 0
Reputation: 336
dateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
will add leading zeros to all lonely, single digits
Upvotes: 1
Reputation: 2546
I think it must be done manually.
var dateString = (d < 10? "0": "") + d + "/" + (m < 10? "0": "") + m + "/" + y;
There are some date formatting libraries/jQuery plugins around, but if this is all you need, they would be an overkill for that.
Upvotes: 2