Reputation: 2260
The expected result is "Last game 2h 12m ago." or "Last game 3m ago.".
Currently it is "Last game 0d 2h 12m ago.", I found nothing in SimpleDateFormat that could do that and the easiest solution I see would be using a StringBuilder, testing whether or not the values are zero each time.
Code sample:
public String getLastgame()
{
long time = ((System.currentTimeMillis() / 60000) - this.config.getLastgameTime());
return ("Last game " + (time / 60) + "h " + (time % 60) + "m ago.");
}
Upvotes: 1
Views: 126
Reputation: 9434
Your time is measured in minutes, so, extract all your time components first:
long oneYear = 60 * 24 * 365;
long oneDay = 60 * 24;
long oneHour = 60;
// extract years
int years = time / oneYear;
// update your time
time = time % oneYear;
// extract days
long days = time / oneDay;
// update your time
time = time % oneDay;
// extract hours
long hours = time / oneHour;
// extract minutes (the remaining)
minutes = time % oneHour;
Then, build your String:
StringBuilder sb = new StringBuilder( "Last time " );
if ( years != 0 ) {
sb.append( years ).append( "y " );
}
if ( days != 0 ) {
sb.append( days ).append( "d " );
}
if ( hours != 0 ) {
sb.append( hours ).append( "h " );
}
if ( minutes != 0 ) {
sb.append( minutes ).append( "m " );
}
sb.append( " ago" );
The complete method will be:
public String getLastgame() {
long time = ((System.currentTimeMillis() / 60000) - this.config.getLastgameTime());
long oneYear = 60 * 24 * 365;
long oneDay = 60 * 24;
long oneHour = 60;
// extract years
int years = time / oneYear;
// update your time
time = time % oneYear;
// extract days
long days = time / oneDay;
// update your time
time = time % oneDay;
// extract hours
long hours = time / oneHour;
// extract minutes (the remaining)
minutes = time % oneHour;
StringBuilder sb = new StringBuilder( "Last time " );
if ( years != 0 ) {
sb.append( years ).append( "y " );
}
if ( days != 0 ) {
sb.append( days ).append( "d " );
}
if ( hours != 0 ) {
sb.append( hours ).append( "h " );
}
if ( minutes != 0 ) {
sb.append( minutes ).append( "m " );
}
sb.append( " ago" );
return sb.toString();
}
Upvotes: 2
Reputation: 3641
Get the index of 'd', 'm' and 'h' in the String. check the value of the characters at index -1 and index-2. If index -2 is a space, check index-1.If it is a 0, remove those indices. And that is 1 way of doing it.
Upvotes: 0