zero in front

S

Sune

How do I allways get day with two digits, not
var dd = d.getDate();
if (dd <10) dd = '0' + dd;
 
D

Dr J R Stockton

In comp.lang.javascript message said:
Sune said the following on 8/31/2007 2:54 PM:

The day will be returned as a number. The only way to get the leading
zero is to convert it to String and add it yourself as you are doing.


Incorrect. There are other ways. One can add 100 and use substring -
and, in VBScript, that seems the most efficient way.

The OP's code sometimes returns String and sometimes Number, which can
be disadvantageous. Consider

D = new Date(1111, 1, 6)
dd = D.getDate();
if (dd <10) dd = '0' + dd
S = (D.getMonth()+1) + dd
which gives 206. Change 6 to 16, and the result is 18.

In any case, if a page needs number-extension more than about twice, a
function should be used.

function LZ(x) { return (x>=10||x<0?"":"0") + x }

The FAQ seems silent on the subject.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,128
Latest member
ElwoodPhil
Top