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.dateLabel, "yyyy-MM-dd", "MMMM YYYY")?.toUpperCase()
public static String formatDate(String inputDate, String inputFormat, String outputFormat) {
try {
Locale appLocale = new Locale(LocaleHelper.getDefaultLanguage());
DateFormat originalFormat = new SimpleDateFormat(inputFormat, appLocale);
DateFormat targetFormat = new SimpleDateFormat(outputFormat);
Date dateObject = originalFormat.parse(inputDate);
String formattedDate = targetFormat.format(dateObject);
return formattedDate;
} catch (ParseException var9) {
return "";
} catch (Exception var10) {
return "";
}
}
There are two major and related problems in your code:
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.utiland their formatting API,SimpleDateFormatare 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.