2

I have 3 fields, day, month, year, and a function to join them. The problem is I need to prepend a zero to the day field if it doesn't have one and is 1 to 9. so what I'm getting for 1st August is

1/08/2015 but what I need is 01/08/2015

So I've been trying variations on str_pad("different stuff attempted", 10, '0', STR_PAD_LEFT)

In both the first line with the var dd and the last line with the r_date with no luck

function join_date()
{
var dd = document.getElementById('day').value;
var mm = document.getElementById('month').value;
var yy = document.getElementById('year').value;
document.getElementById('dr_date').value =  (('0'+dd).slice(-2)+"/"+mm+"/"+yy)

}
Kilisi
  • 402
  • 11
  • 33
  • possible duplicate of [How can I create a Zerofilled value using JavaScript?](http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript) – Siamak Ferdos Aug 01 '15 at 04:26
  • never mind I worked it out by changing the last line to document.getElementById('dr_date').value =(('0' + dd).slice(-2)+"/"+mm+"/"+yy) – Kilisi Aug 01 '15 at 04:34
  • 1
    @Kilisi using that (`('0'+dd).slice(-2)`) is more expensive than just doing an `if-then-else`. You're concatenating and then getting a substring. – Alejandro Iván Aug 01 '15 at 04:42
  • I didn't know that, I'm very very new to js, I'm going to use the answer you gave. – Kilisi Aug 01 '15 at 04:46

1 Answers1

4

In Javascript, concatenating ("adding") strings is done with the + operator (as I assume you already know). Just check if the value is less than 10 (thus it needs a 0 prepended) and edit it. Otherwise don't modify the string.

var dd = document.getElementById('day').value;
var mm = document.getElementById('month').value;
var yy = document.getElementById('year').value;

/*
    The next is equivalent to:

    if ( dd < 10 ) dd = "0" + dd;
    else dd = dd;

    The same goes for the month.
*/
dd = dd < 10 ? "0" + dd : dd;
mm = mm < 10 ? "0" + mm : mm;

document.getElementById('r_date').value =(dd+"/"+mm+"/"+yy)
Alejandro Iván
  • 3,969
  • 1
  • 21
  • 30