Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Time Formatting
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
jacklarry




PostPosted: 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.
Sponsor
Sponsor
Sponsor
sponsor
richcash




PostPosted: 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.
HeavenAgain




PostPosted: 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]
TheFerret




PostPosted: 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
richcash




PostPosted: 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.
HeavenAgain




PostPosted: 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
Euphoracle




PostPosted: Tue Oct 16, 2007 2:12 pm   Post subject: RE:Time Formatting

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




PostPosted: Tue Oct 16, 2007 3:50 pm   Post subject: RE:Time Formatting

alrite thnx a lot guys
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 8 Posts ]
Jump to:   


Style:  
Search: