0

My app has a 0 - 120 minute picker. I want to display the time like this: "In ... minutes".

I found the method DateUtils#getRelativeTimeSpanString(long, long, long) and it works correctly for values under 60 minutes. However, if the value is 60 minutes or higher it displays it as "In 1 hour" instead of "In 120 minutes".

This is the code I'm using:

int minutes = 70;
long millis = minutes * 60 * 1000;
String text = DateUtils.getRelativeTimeSpanString(millis, 0L, DateUtils.MINUTE_IN_MILLIS);
myTextView.setText(text); // Displays "In 1 hour" instead of "In 70 minutes".

How can I force the output to be in minutes?

Thomas Vos
  • 12,271
  • 5
  • 33
  • 71
  • You can also try to use a string resource and calculate the minutes to achieve what you want. – Gabriel Costa Oct 16 '17 at 13:53
  • Well, maybe there is a way to do that with java, but why using `getRelativeTimeSpanString` while you have already minutes? –  Oct 16 '17 at 13:55
  • @GabrielCosta I would like to use the default Android strings if possible, because they are already translated. – Thomas Vos Oct 16 '17 at 14:41
  • @Ibrahim I would like to use the default Android strings if possible, because they are already translated. – Thomas Vos Oct 16 '17 at 14:42
  • @Ibrahim Sorry, but I don't see how that is related. The method you showed converts milliseconds to minutes. I need a String to show in e.g. a TextView. Did you test the code in my question? See the documentation at: https://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString(long,%20long,%20long) – Thomas Vos Oct 16 '17 at 14:49

1 Answers1

0

Based on the comments, you can use a string resource. First, create a plural resource, to support both "In 1 minute" and "In 2 minutes":

<plurals name="time_remaining_in_minutes">
        <item quantity="one">In %1$d minute</item>
        <item quantity="other">In %1$d minutes</item>
</plurals>

Then, call it inside your code:

int minutes = 70;
long millis = minutes * 60 * 1000;
String text = getResources.getQuantityString(R.plurals.time_remaining_in_minutes, minutes, minutes);
myTextView.setText(text);
Gabriel Costa
  • 341
  • 1
  • 10
  • I know this is possible, but as I replied to your comment, I want to use the default Android strings. (They are already translated in many languages). – Thomas Vos Oct 16 '17 at 15:34
  • Sorry, I misunderstood your answer. I thought you meant string resources insted of Android strings. Well, if that's worth, you can create strings.xml files for other languages (manually). – Gabriel Costa Oct 16 '17 at 15:40