0

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.

user2571510
  • 11,167
  • 39
  • 92
  • 138
  • 3
    possible duplicate of [Javascript add leading zeroes to date](http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date) – Wilmer Apr 01 '14 at 19:30
  • 6
    how about `('0' + d).substr(-2)` or `('0' + d).slice(-2)` (*for IE support*) ? – Gabriele Petrioli Apr 01 '14 at 19:31
  • Thanks, this looks great too and is less code than the below. Can you explain what the substr(-2) will do here ? – user2571510 Apr 01 '14 at 19:43
  • @user2571510 - for this purpose, it does pretty much the same thing for strings that `slice` does for arrays, however, I think it is more expensive than a comparison and a concatenation. If the code is not performance sensitive, either would work. Heh, it is only one character shorter. – PhistucK Apr 01 '14 at 19:50
  • `substr` or better `slice` with a negative value for the `start` parameter will start counting from the end. (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) – Gabriele Petrioli Apr 02 '14 at 12:45

3 Answers3

2

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.

PhistucK
  • 2,466
  • 1
  • 26
  • 28
1
dateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');

will add leading zeros to all lonely, single digits

Povesma Dmytro
  • 326
  • 2
  • 6
0

Try following

var d_str = ("00" + d).slice(-2);
var m_str = ("00" + m).slice(-2);
var dateString_formatted = d_str + "/" + m_str + "/" + y;
  • While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained. – borchvm Apr 30 '20 at 08:03