Convert Seconds Into Time in Java

Convert Seconds Into Time in Java


Posted in : Java Posted on : August 19, 2011 at 5:42 PM Comments : [ 0 ]

In this tutorial you will learn how to convert seconds into time/timeformat.

Convert Seconds Into Time in Java

In this tutorial you will learn how to convert seconds into time/timeformat.

Here I am giving a simple example for converting seconds into a time string. In the example given below I have done some mathematical processes such as to find hour divided the input seconds by 3600 and also find the remainder by using the mod operator then divided the founded remainder by 60 to find the minute and finally find a remainder of the remainder which has been found in early step by using mod operator.

Example :

SecToTime.java

import java.util.Scanner;

class SecToTime
{
public static void main (String arr[])
{
int hr;
int mn;
int sec;
System.out.println("Second To Time Converter");
System.out.println("");
System.out.println("Enter the time in seconds");
Scanner scan = new Scanner(System.in);
long s = scan.nextLong();
hr = (int)(s/3600);
int rem = (int)(s%3600);
mn = rem/60;
sec = rem%60;
String hrStr = (hr<10 ? "0" : "")+hr;
String mnStr = (mn<10 ? "0" : "")+mn;
String secStr = (sec<10 ? "0" : "")+sec; 
System.out.println(hrStr+ " : "+mnStr+ " : "+secStr);
}
}

Output :

When you will compile and execute the above example you will get the output as :

1. compile

2. execute

3. Enter the value

4. Final Output

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics