xceph
xceph

Reputation: 1046

Inconsistent date formatting, possibly due to locale?

I've noticed that some users of my app are experiencing oddly formatted dates, and I am assuming it is due to locale reasons. Can someone suggest a better way to achieve the expected result and/or explain how to properly deal with the (possible) locale issue?

Time time = new Time();
time.setToNow();
String timeString = time.format("%b_%d_%Y_%I-%M-%S-%p");

Expected result:

Feb_12_2014_10-06-09-AM

From my logging I occasionally see results like this:

2?_12_2014_07-35-58-??

sadly I do not capture the locale info so I don't know the exact details.

edit: After trying the accepted solution here are the results for each locale on Android.

en_ca Feb_12_2014_10-49-52-AM
fr_CA févr._12_2014_10-49-52-AM
en_ca Feb_12_2014_10-49-52-AM
zh_CN 2?_12_2014_10-49-52-AM
zh 2?_12_2014_10-49-52-AM
en Feb_12_2014_10-49-52-AM
fr_FR févr._12_2014_10-49-52-AM
fr févr._12_2014_10-49-52-AM
de Feb._12_2014_10-49-52-AM
de_DE Feb._12_2014_10-49-52-AM
it_IT feb_12_2014_10-49-52-AM
ja 2?_12_2014_10-49-52-AM
ko_KR 2?_12_2014_10-49-52-??
ko 2?_12_2014_10-49-52-??
zh_CN 2?_12_2014_10-49-52-AM
<none> 2_12_2014_10-49-52-AM
zh_CN 2?_12_2014_10-49-52-AM
zh_TW 2?_12_2014_10-49-52-??
en_GB Feb_12_2014_10-49-52-AM
en_US Feb_12_2014_10-49-52-AM

Upvotes: 0

Views: 75

Answers (1)

laalto
laalto

Reputation: 152817

Use a SimpleDateFormat to format your datetime strings. It has a constructor that allows you to specify the Locale, for example Locale.US.

Time.format() always works with the current, user-chosen locale which may not be what you want.

Further reading: Be wary of the default locale

Upvotes: 1

Related Questions