I am using SimpleDateFormat class to get current year like this
SimpleDateFormat currentYear = new SimpleDateFormat("YYYY");
Date thisYear = new Date();
String stringThisYear = currentYear .format(thisYear );
It is working fine in here(India) ,but it crashed when it run on Malaysia by other people.After lot of debugging and searching ,i found that it is happening due to no mention of locale.So I changed my code to this
SimpleDateFormat currentDate = new SimpleDateFormat("YYYY", Locale.ENGLISH);
Still it is crashing, so I use calendar instance to get current year like this
int thisYear=Calendar.getInstance().get(Calendar.YEAR);
But i want to know what is issue with simpleDateFormat as most of my code is already has simpleDateFormat class.So I want to know the reason for crash,if anyone has solution,Please help me.Thank you
It's because you must use "yyyy" instead of "YYYY"
On old versions of Android, using "YYYY" makes your app to crash. Nothing to do with the country/Locale
"Y" stands for week year and not year, as specified in the Javadoc
EDIT 2
More information here
yyyy is the pattern string to identify the year in the SimpleDateFormat class.
Java 7 introduced YYYY as a new date pattern to identify the date week year.
An average year is exactly 52.1775 weeks long, which means that eventually a year might have either 52 or 53 weeks considering indivisible weeks.
Using YYYY unintendedly while formatting a date can cause severe issues in your Java application.
As mentioned by @OleV.V., the format Y
is only supported on Android API 24+. Using any versions below API 24 makes the app to crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With