How to use String.format(Locale, ...)?

1.4k views Asked by At

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.

1

There are 1 answers

2
Gabe Sechan On

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.)