Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App crashes when I use SimpleDateFormat class with "YYYY"

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

like image 233
camelCode Avatar asked Jan 29 '23 00:01

camelCode


1 Answers

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.

like image 61
Eselfar Avatar answered Jan 31 '23 08:01

Eselfar