
-----------------------------------
jacklarry
Mon Oct 15, 2007 8:38 pm

Time Formatting
-----------------------------------
Hi,
Can you guys please tell me how you can make the time in "HH:MM" format? so that even if the user inputs the value 5 for minutes, it will output "05" instead of simply "5". Same with the hours. Thanks a lot in advance.

-----------------------------------
richcash
Mon Oct 15, 2007 9:07 pm

Re: Time Formatting
-----------------------------------
Well, one quick way would be to check if the minutes or hours are less than 10. If so, add a "0" in front.

if (hours < 10) {
   System.out.print("0");
}
System.out.print(hours + ":");
if (minutes < 10) {
   System.out.print("0");
}
System.out.println(minutes);

This is all assuming that hours and minutes are separate variables, of course.

-----------------------------------
HeavenAgain
Mon Oct 15, 2007 10:39 pm

RE:Time Formatting
-----------------------------------
why do i think there is a shorter way for this, probably just 
1 or 2 lines shorter?[wonders]........[/wondering]

-----------------------------------
TheFerret
Mon Oct 15, 2007 10:45 pm

RE:Time Formatting
-----------------------------------
http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

-----------------------------------
richcash
Mon Oct 15, 2007 10:57 pm

Re: Time Formatting
-----------------------------------
Yeah, I suppose using the class TheFerret is showing may be shorter.

But don't forget that my above code can be shortened to :
System.out.println((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes);
which is pretty short and doesn't require looking up methods.

-----------------------------------
HeavenAgain
Mon Oct 15, 2007 10:58 pm

RE:Time Formatting
-----------------------------------
dam! i just thought of it too :P System.out.printf();
that is what you are looking for, probably. :lol:

-----------------------------------
Euphoracle
Tue Oct 16, 2007 2:12 pm

RE:Time Formatting
-----------------------------------
What about String.format?  It has options for date/time formatting.

-----------------------------------
jacklarry
Tue Oct 16, 2007 3:50 pm

RE:Time Formatting
-----------------------------------
alrite thnx a lot guys
