I need to format my time string such as this:
int time = 160;
Here's my sample code:
public static String formatDuration(String minute) {
String formattedMinute = null;
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse(minute);
sdf = new SimpleDateFormat("HH mm");
formattedMinute = sdf.format(dt);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedMinute;
// int minutes = 120;
// int h = minutes / 60 + Integer.parseInt(minute);
// int m = minutes % 60 + Integer.parseInt(minute);
// return h + "hr " + m + "mins";
}
I need to display it as 2hrs 40mins. But I don't have a clue how to append the "hrs" and "mins". The requirement is not to use any library.
If you've done something like this in the past, feel free to help out. Thanks a bunch!
Since, it's 2018, you really should be making use of the Date/Time libraries introduced in Java 8
Which outputs...
Why use something like this? Apart of generally been a better API, what happens when
minutes
equals something like1600
?Instead of printing
2hrs 40mins
, the above will display26hrs 40mins
.SimpleDateFormat
formats date/time values, it doesn't deal with durationJust try
There is a good documentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html From the doc:
Get the string you're making and split it by whatever character is separating the values, i.e ' ', or ':'
Then do
Another simple approach could be something along the lines: