【问题标题】:YYYY date format returns 2021 on one device and 2020 on other device [duplicate]YYYY 日期格式在一台设备上返回 2021,在另一台设备上返回 2020 [重复]
【发布时间】: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 "";
        }
    }

【问题讨论】:

标签: android date datetime-format simpledateformat android-date


【解决方案1】:

您的代码中有两个主要的相关问题:

  1. 在没有Locale 的情况下使用SimpleDateFormat:您在没有Locale 的情况下使用了new SimpleDateFormat(outputFormat),因此很容易出错。检查this answer 以了解更多关于由于缺少Locale 而可能出现的问题。由于您的预期输出是英文,请使用英文类型 Locale 例如new SimpleDateFormat(outputFormat, Locale.ENGLISH)。
  2. Y 用于Week year 和SimpleDateFormat,它是区域设置敏感的,即它可能对不同的区域设置有不同的值。检查this discussion 了解更多信息。从您的问题来看,您的意思似乎是 Year 而不是 Week year,因此,您应该使用 y,正如您在 inputFormat 中已经指定的那样。

java.util 的日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用,转用modern date-time API。

从 Trail: Date Time 了解现代日期时间 API。

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    相关资源
    最近更新 更多