Yyyy Date Format Returns 2021 On One Device And 2020 On Other Device
I am trying to format the date using the below code. 2021-01-02 returns JANUARY 2020 in one device and JANUARY 2021 on another device. Why is it so? formatDate(transactionItem.date
Solution 1:
There are two major and related problems in your code:
- Using
SimpleDateFormatwithoutLocale: You have usednew SimpleDateFormat(outputFormat)without aLocaleand as such, it is error-prone. Check this answer to learn more about the problem that may occur due to lack ofLocale. Since your expected output is in English, use the English type ofLocalee.g.new SimpleDateFormat(outputFormat, Locale.ENGLISH). Yis used for Week year and forSimpleDateFormat, it is Locale-sensitive i.e. it may have different values for different locales. Check this discussion to learn more about it. From your question, it looks like you meanYearand notWeek yearand therefore, you should useyas already specified in yourinputFormat.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Learn about the modern date-time API from Trail: Date Time.
Post a Comment for "Yyyy Date Format Returns 2021 On One Device And 2020 On Other Device"