Skip to content Skip to sidebar Skip to footer

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:

  1. Using SimpleDateFormat without Locale: You have used new SimpleDateFormat(outputFormat) without a Locale and as such, it is error-prone. Check this answer to learn more about the problem that may occur due to lack of Locale. Since your expected output is in English, use the English type of Locale e.g. new SimpleDateFormat(outputFormat, Locale.ENGLISH).
  2. Y is used for Week year and for SimpleDateFormat, 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 mean Year and not Week year and therefore, you should use y as already specified in your inputFormat.

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.

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"