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.