patternjavaMajor
Integer seconds to formated string mm:ss
Viewed 0 times
formatedsecondsintegerstring
Problem
I have a
String like "Time left (XX)" or "You need stay here for (XX)" and int as second. I use those two variables to format label like "string (mm:ss)" example "Time left (59:23)".private String timeDescription(String pDescription,int pTime) {
final String preformatedTime = secondsToString(pTime);
final String timeForReturn = putTimeInXX(pDescription,preformatedTime);
return timeForReturn;
}
private String secondsToString(int pTime) {
final int min = pTime/60;
final int sec = pTime-(min*60);
final String strMin = placeZeroIfNeede(min);
final String strSec = placeZeroIfNeede(sec);
return String.format("%s:%s",strMin,strSec);
}
private String placeZeroIfNeede(int number) {
return (number >=10)? Integer.toString(number):String.format("0%s",Integer.toString(number));
}
private String putTimeInXX(String pDescription,String pTime) {
String[] apartDescription = pDescription.split("XX");
StringBuilder descriptionForReturn = new StringBuilder();
for (int i = 0; i < apartDescription.length; i++) {
descriptionForReturn.append(apartDescription[i]);
if (i == 0) {
descriptionForReturn.append(pTime);
}
}
return descriptionForReturn.toString();
}Solution
Your code looks functional, and, if this was for early versions of Java, it would be quite typical and standard.
The
Your function:
can be simplified drastically by using more of the
The
Note, that using the modulo 60
The
String.format process can do so much more than what you are using it for, though.Your function:
private String secondsToString(int pTime) {
final int min = pTime/60;
final int sec = pTime-(min*60);
final String strMin = placeZeroIfNeede(min);
final String strSec = placeZeroIfNeede(sec);
return String.format("%s:%s",strMin,strSec);
}can be simplified drastically by using more of the
String.format functionality:private String secondsToString(int pTime) {
return String.format("%02d:%02d", pTime / 60, pTime % 60);
}The
%02d means: "Format as a decimal number using at least 2 digits, and pad with 0 if less than 2 digits"Note, that using the modulo 60
pTime % 60 gets the remainder of seconds when dividing by 60. This is short hand for pTime - (ptime / 60) * 60Code Snippets
private String secondsToString(int pTime) {
final int min = pTime/60;
final int sec = pTime-(min*60);
final String strMin = placeZeroIfNeede(min);
final String strSec = placeZeroIfNeede(sec);
return String.format("%s:%s",strMin,strSec);
}private String secondsToString(int pTime) {
return String.format("%02d:%02d", pTime / 60, pTime % 60);
}Context
StackExchange Code Review Q#59784, answer score: 23
Revisions (0)
No revisions yet.