问题描述
我正在尝试使用以下代码格式化日期。
2021-01-02 在一台设备上返回 2020 年 1 月,在另一台设备上返回 2021 年 1 月。为什么会这样?
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 "";
}
}
解决方法
您的代码中有两个主要的相关问题:
- 在没有
SimpleDateFormat
的情况下使用Locale
:您在没有new SimpleDateFormat(outputFormat)
的情况下使用了Locale
,因此很容易出错。检查 this answer 以了解有关由于缺少Locale
而可能出现的问题的更多信息。由于您的预期输出是英文,请使用Locale
的英文类型,例如new SimpleDateFormat(outputFormat,Locale.ENGLISH)
。 -
Y
用于 Week year 和SimpleDateFormat
,它是 Locale-sensitive,即对于不同的 locale,它可能具有不同的值。检查 this discussion 以了解更多信息。从您的问题来看,您的意思是Year
而不是Week year
,因此,您应该使用y
中已指定的inputFormat
。
java.util
的日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到 modern date-time API。
- 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7。
- 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
从 Trail: Date Time 了解现代日期时间 API。