I am trying to display following message in one of my application to show the waiting time
2 hours, 3 mins and 4 s
1 hour and 2 s
As you can see there can be many variations and I am struggling to get this done. The following code works well is the given number of secs gives out non-zero hr, min and sec, but this is getting completed if I have to handle the case where only I have hours and secs to display and no minutes to display.
Also not sure where to add those string 'and' and the comma.
I believe there should be already a solution for this which I may not know.
public class HumanizedWaitDisplay {
public static void main(String[] args) {
int noOfSecToWait = 60*60*2 + 30;
System.out.println("Waiting for " + getHumanizedTime(noOfSecToWait));
}
private static String getHumanizedTime(int seconds) {
String out ="";
int hr = seconds/(60*60);
seconds = seconds%(60*60);
int min = seconds/(60);
seconds = seconds%(60);
if(hr>0) {
out += hr + " hour" +(hr == 1 ? " ":"s ");
}
if(min > 0){
out += min + " min" +(min == 1 ? " ":"s ");
}
if(seconds > 0){
out += seconds + " s";
}
return out;
}
}
Let me know if you have come across such thing.
You can use the java date and time api. Brief example (using the method signature you provided at question body) :
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); //specifiy the
//representation pattern. This is for example. You can construct it more accurate:
//display the hours, mins, secs, etc. Also you can specify your own delimiters.
//See more at docs below
static { //upd: set the proper timezone
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
}
private static String getHumanizedTime(int seconds) {
long timeInMillis = seconds * 1000; //Date object is designed for millis
Date date = new Date(timeInMillis);
return dateFormat.format(date);
}
Read more at javadocs : http://docs.oracle.com/javase/6/docs/api/java/util/Date.html http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
Update : if you want the output to be something like "11 hours, 15 minutes and 34 seconds", try that :
static DateFormat dateFormat = new SimpleDateFormat("HH 'hours,' mm 'minutes and' ss 'seconds'");