Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can I add 0's to single numbers in a getDate script? 2

Status
Not open for further replies.

ZekeO238

Programmer
Oct 1, 2002
32
US
The script I have now, like all others I have seen, displays 10.1.2002 on the screen. I would liek it to instead display 10.01.2002. There is a reason I want this, I have my date set on an image so when the date becomes bigger or smaller it is off-center on the image. Is this possible?
 
Im obviously not a Javascript expert, I was playing around with the script, and although this doesnt WORK, this is pretty much the way I want it to work.

<script language=&quot;Javascript&quot;>
<!--
var date=new Date()
var month=date.getMonth()+1
var day=date.getDate()
if (day>10) &quot;0&quot;+day
var year=date.getYear()
if (year<200) year+1900

document.write(month + &quot;.&quot; + day + &quot;.&quot; + year)
-->
</script>


As you can see, it says if the day is less than 10 (i.e. 1-9) than to add a 0 then the day number, but it doesnt work. That really did look like it would work though!
 
it was closetry this
<script language=&quot;Javascript&quot;>
var date = new Date()
var month = date.getMonth()+1
var day = date.getDate()
var year = date.getYear()
if (day<10) { day = &quot;0&quot;+day }
if (month<10) { month = &quot;0&quot;+month }

document.write(month + &quot;.&quot; + day + &quot;.&quot; + year)
</script> A language that doesn't affect the way you think about programming is not worth knowing.
admin@onpntwebdesigns.com
 
Thanks! Thats exactly what I needed. I was pretty close, wasnt I?
 
onpt,

How about extending the JavaScript Date object to handle this kind of thing?

Date.prototype.paddedDate = function()
{
var month = this.getMonth()+1
var day = this.getDate()
return ((day < 10) ? &quot;0&quot;+day : day) + &quot;.&quot;
+((month<10) ? &quot;0&quot;+month : month) + &quot;.&quot;
+ this.getYear())
}

Now if you need to use paddedDate somewhere you simply create your date the way you normally do it and call the method paddedDate() on it! :)

var today = new Date();
document.write(today.paddedDate());

Cleans up the code a bit doesn't it? Gary Haran
 
very nice Gary
I think I remember you posting something simular a few months ago.

Changed a few ways I do things here. [thumbsup2] A language that doesn't affect the way you think about programming is not worth knowing.
admin@onpntwebdesigns.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top