0

I am new in Android development and I'm trying this code:

String hms = String.format("%02d:%02d:%02d",
               TimeUnit.MILLISECONDS.toHours(milliSeconds),
               TimeUnit.MILLISECONDS.toMinutes(milliSeconds) - 
               TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliSeconds)),
               TimeUnit.MILLISECONDS.toSeconds(milliSeconds) -
               TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds)));

I get the message :

Implicitly using the default locale is a common source of bugs:

Use String.format(Locale, ...) instead

I have no idea how to modify the code in order to implement the recommendation.

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
  • 1
    To get rid of the warning insert `Locale.getDefault(Locale.Category.FORMAT)` as the first argument before the format string. It won’t change the behaviour (so also won’t get rid of any bug if there was one, which I don’t think). – Ole V.V. Apr 14 '22 at 10:05
  • BTW for an even more elegant and less error-prone way of formatting milliseconds to hours-minutes-seconds since Java 9 define `Duration dur = Duration.ofMillis(milliSeconds);` and pass `dur.toHours(), dur.toMinutesPart(), dur.toSecondsPart()` as the arguments to be formatted. – Ole V.V. Apr 14 '22 at 10:14

1 Answers1

1

Most likely you don't need to do anything. That's a warning telling you that you didn't specify a locale for String.format, so it's using the default locale. That can cause a bug in some circumstances, but it's unlikely to in yours. If you want to be careful you can pass in an explicit locale, or you can just ignore the warning. Formatting numbers like this without any type of currency is fairly safe.

(The bugs you'll see are if the locale your device is in has specific formatting rules for things. The big one I know of that's hit me is that Turkish has a letter i who's capital symbol is different than the english letter I.)

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • 2
    another Locale-specific is the decimal point – user16320675 Apr 12 '22 at 15:53
  • @user16320675 Good point (no pun intended, or perhaps). Estimated programmers have used `format` with no locale arg to format into like `2.4` and have been very surprised when one day `2,4` (with a comma) comes out. Users may be happy, but if for instance you try to parse it back with `Double.parseDouble()`, it will suddenly break the day that happens. – Ole V.V. Apr 14 '22 at 10:35