YYYY日期格式在一台设备上返回2021,在另一台设备上返回2020 [英] YYYY date format returns 2021 on one device and 2020 on other device
本文介绍了YYYY日期格式在一台设备上返回2021,在另一台设备上返回2020的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下代码设置日期格式.
I am trying to format the date using the below code.
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 "";
}
}
推荐答案
您的代码中存在两个主要且相关的问题:
There are two major and related problems in your code:
- 在没有
Locale
的情况下使用SimpleDateFormat
:您已经在没有Locale
的情况下使用了new SimpleDateFormat(outputFormat)
,这很容易出错.检查此答案,以详细了解由于缺少Locale
而可能发生的问题.由于您的预期输出为英语,因此请使用Locale
的英语类型,例如new SimpleDateFormat(outputFormat,Locale.ENGLISH)
. -
Y
用于此讨论以了解更多信息.从您的问题看来,您的意思是Year
,而不是Week year
,因此,您应该使用y
,已经在中指定了inputFormat
.
- Using
SimpleDateFormat
withoutLocale
: You have usednew SimpleDateFormat(outputFormat)
without aLocale
and 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 ofLocale
e.g.new SimpleDateFormat(outputFormat, Locale.ENGLISH)
. Y
is 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 meanYear
and notWeek year
and therefore, you should usey
as already specified in yourinputFormat
.
java.util
的日期时间API及其格式API SimpleDateFormat
已过时且容易出错.建议完全停止使用它们,并切换到现代日期时间API .
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.
- 出于任何原因,如果您必须坚持使用Java 6或Java 7,则可以使用 ThreeTen-Backport ,它将大多数 java.time 功能反向移植到Java 6&7.
- 如果您正在为Android项目工作,并且您的Android API级别仍不符合Java-8,请检查如何在Android Project中使用ThreeTenABP .
- 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.
通过 Trail:日期了解有关现代日期时间API的信息时间 .
Learn about the modern date-time API from Trail: Date Time.
这篇关于YYYY日期格式在一台设备上返回2021,在另一台设备上返回2020的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文