YYYY日期格式在一台设备上返回2021,在另一台设备上返回2020 [英] YYYY date format returns 2021 on one device and 2020 on other device

查看:57
本文介绍了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:

  1. 在没有 Locale 的情况下使用 SimpleDateFormat :您已经在没有 Locale 的情况下使用了 new SimpleDateFormat(outputFormat),这很容易出错.检查此答案,以详细了解由于缺少 Locale 而可能发生的问题.由于您的预期输出为英语,因此请使用 Locale 的英语类型,例如 new SimpleDateFormat(outputFormat,Locale.ENGLISH).
  2. Y 用于此讨论以了解更多信息.从您的问题看来,您的意思是 Year ,而不是 Week year ,因此,您应该使用 y ,已经在中指定了inputFormat .
  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.

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.

  • 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆