This question already has an answer here:
I have counter, you set a date, and then you can get time to this date, but I need display it in chosen format.
EG: If I have 1 day, 13 hours, 43 minutes and 30 seconds left, and set format to:
"You have: #d# days, #h# hours, #m# minutes to die"
Then just display:
"You have 1 day, 13 hours, 43 minutes to die"
But if you set format to:
"You have: #h# hours, #m# minutes to die"
Then I need display:
"You have 37 hours, 43 minutes to die"
(so missing type (days) are converted to other (hours))
I have this code: PS: S,M,H,D,W that just second in milliseconds, minutes in milliseconds etc...
public static String getTimerData(long time, String format) {
int seconds = -1, minutes = -1, hours = -1, days = -1, weeks = -1;
if (format.contains("#s#")) {
seconds = (int) (time / S);
}
if (format.contains("#m#")) {
if (seconds == -1) {
minutes = (int) (time / M);
} else {
minutes = (seconds / 60);
seconds %= 60;
}
}
if (format.contains("#h#")) {
if (minutes == -1) {
hours = (int) (time / H);
} else {
hours = (minutes / 60);
minutes %= 60;
}
}
if (format.contains("#d#")) {
if (hours == -1) {
days = (int) (time / D);
} else {
days = (hours / 24);
hours %= 24;
}
}
if (format.contains("#w#")) {
if (days == -1) {
weeks = (int) (time / W);
} else {
weeks = (days / 7);
days %= 7;
}
}
return format.replace("#w#", Integer.toString(weeks)).replace("#d#", Integer.toString(days)).replace("#h#", Integer.toString(hours)).replace("#m#", Integer.toString(minutes)).replace("#s#", Integer.toString(seconds));
}
And... any better way to do that?
Joda-Time
If your goal is the words spelling out "1 day, 13 hours, and 43 minutes", then Joda-Time has a class exactly for that purpose:
PeriodFormatterBuilder
. Using that class is easier that trying to write your own. See examples in other answers such as this one and this one.java.time.*
The new java.time.* package in Java 8 may have something similar given that it is inspired by Joda-Time. Perhaps the
DateTimeFormatterBuilder
class in the java.time.format package.more info here
or, if you're not using java8 here