YYYY 日期格式在一台设备上返回 2021,在另一台设备上返回 2020

问题描述

我正在尝试使用以下代码格式化日期。

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 "";
        }
    }

解决方法

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

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

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

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