【发布时间】:2021-04-08 17:21:21
【问题描述】:
我正在尝试使用以下代码格式化日期。
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 "";
}
}
【问题讨论】:
-
设备上设置的区域设置是什么?
-
@Stachu appLocale 为两个设备返回 en
-
"YYYY" 是周年,与日历年不同(请参阅stackoverflow.com/questions/34691582/…)。我不知道为什么两个设备不同,但可能的原因是不同的语言环境(导致使用不同的日历),或者 Android API 级别(根据developer.android.com/reference/java/text/SimpleDateFormat,API 24 中引入了周年“YYYY”)
-
这能回答你的问题吗? How does Java "week year" really work?
标签: android date datetime-format simpledateformat android-date