Reputation: 1022
I was parsing date strings using Spanish Locale with SimpleDateFormat
in an Android project and for some strange reason I was getting ParseException
only with dates that had September as a month. Not knowing why this behaviour took place, I decided to create a toy program in Eclipse with a date string that was throwing this exception, in order to reproduce this bug. To my surprise, no exception was thrown and the date was parsed correctly.
So my question is: why does the first block of code (with jdk 1.8_25) does not throw a ParseException
, while the second block of code (in an empty Android Studio application, with SDK 21 rev.2 and Build-Tools 21.1.2) throws a ParseException
? Can anyone else reproduce this strange behaviour? What am I doing wrong? Shouldn't in both cases the strings be parsed correctly as dates?
Code #1 (jdk 1.8_25):
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
private static final String THIS_YEAR_TIME_FORMAT = "d 'de' MMM, HH:mm";
private static final DateFormat THIS_YEAR_TIME_FORMATTER = new SimpleDateFormat(THIS_YEAR_TIME_FORMAT,
new Locale("es", "ES"));
public static void main(String[] args) {
final String problemStr = "3 de sep, 22:50";
Date time;
try {
time = THIS_YEAR_TIME_FORMATTER.parse(problemStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Code #2 (Android SDK 21 rev.2, Build-Tools 21.1.2):
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends ActionBarActivity {
private static final String THIS_YEAR_TIME_FORMAT = "d 'de' MMM, HH:mm";
private static final DateFormat THIS_YEAR_TIME_FORMATTER = new SimpleDateFormat(THIS_YEAR_TIME_FORMAT,
new Locale("es", "ES"));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String problemStr = "3 de sep, 22:50";
Date time;
try {
time = THIS_YEAR_TIME_FORMATTER.parse(problemStr);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Upvotes: 2
Views: 635
Reputation: 15476
Looks like "sept." is the proper Spanish September/septiembre abbreviation according to CLDR, which Android uses. For Java, CLDR support is only added in Java 8 and is not used by default, Java default implementation is not 100% compatible with that of CLDR, guess this is one of the incompatibilities.
Looks like it's a major bug in Android 5.0+...
The code works on Galaxy S3 (Android 4.3) & Android 4.4 emulator, but fails on both Android 5.0 emulator and Nexus 7 (2013) running 5.0.1. Even using a Locale
instance returned by Locale.getAvailableLocales()
would fail on Android 5.0.x.
Google giveth and Google taketh away, I guess.
Upvotes: 2