Computer Science Canada

Time Formatting

Author:  jacklarry [ Mon Oct 15, 2007 8:38 pm ]
Post subject:  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.

Author:  richcash [ Mon Oct 15, 2007 9:07 pm ]
Post subject:  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.
Java:

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.

Author:  HeavenAgain [ Mon Oct 15, 2007 10:39 pm ]
Post subject:  RE:Time Formatting

why do i think there is a shorter way for this, probably just
1 or 2 lines shorter?[wonders]........[/wondering]

Author:  TheFerret [ Mon Oct 15, 2007 10:45 pm ]
Post subject:  RE:Time Formatting

http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

Author:  richcash [ Mon Oct 15, 2007 10:57 pm ]
Post subject:  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 :
Java:
System.out.println((hours < 10 ? "0" : "") + hours + ":" + (minutes < 10 ? "0" : "") + minutes);

which is pretty short and doesn't require looking up methods.

Author:  HeavenAgain [ Mon Oct 15, 2007 10:58 pm ]
Post subject:  RE:Time Formatting

dam! i just thought of it too Razz System.out.printf();
that is what you are looking for, probably. Laughing

Author:  Euphoracle [ Tue Oct 16, 2007 2:12 pm ]
Post subject:  RE:Time Formatting

What about String.format? It has options for date/time formatting.

Author:  jacklarry [ Tue Oct 16, 2007 3:50 pm ]
Post subject:  RE:Time Formatting

alrite thnx a lot guys


: