Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to set time in hh:mm:ss Format?

 
chinna
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is my code..

class TimeFormat
{
public static void main(String ar[])
{
long sec=3650;
long min=0;
int hour=0;
while(sec>=60)
{
sec=sec-60;
min++;
while(min>=60)
{
min=min-60;
hour++;
}
}
System.out.println(hour+":"+min+":"+sec);
}
}

output: 1:0:50..... but i want it in 01:00:50

Friends please help regarding this..,

Thanks in advance
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Is your name really "java?" You know there is a policy about names on the Ranch?

There are several ways of setting time format.
  • 1: Find a class which does it for you. SimpleDateFormat is a possibility; I haven't used it myself.
  • 2: Use the formatting capabilities described in Formatter, (the same method is described in the Java Tutorial).
  • 3: There are probably classes in things like Jakarta Commons which will do the same for you.
  • Using formatted Strings (no 2) is the nearest to what you are doing already.

    CR
     
    Campbell Ritchie
    Sheriff
    Posts: 48652
    56
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    BTW: You will get a far more elegant solution to adding times by using the % operator rather than "-60".
     
    Wayan Saryada
    Ranch Hand
    Posts: 105
    IntelliJ IDE MySQL Database Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hi,

    You can try to use System.out.printf() method to format your printing output.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic