Android - 显示不同日期格式的月份名称

Android - Displaying month name for different date formats

我有一个应用程序以本地化格式显示不同地区的日期和时间,也就是说 - 它显示了用户日期和时间根据他的喜好。但我的问题是它总是显示数字,即yyyy.mm.dd,或mm/dd/yyy,或 dd,mm,yyyy。我想要的是:显示日期,以便日是数字,年是数字,但月份显示为字符串,即。 Jan / Xin / Gen / Jān / Yan... or 01 Jan 2018 / Jan 01 2018 / 2018 Jan 01,依此类推,但仍保持当前本地格式。我知道如果我像 MMM 一样对它进行硬编码,我可以做到这一点,但我希望它根据本地化格式进行更改。

所以基本上这是我的问题:如何根据我从服务器获得的值显示本地化时间 (yyyy-MM-dd HH: mm: ss),月份显示为三个字母的单词,无论它使用什么语言环境?

我知道这个问题听起来很熟悉,但到目前为止我已经尝试了很多关于堆栈溢出和其他来源的答案,但都没有成功。我尝试过的一些事情包括:1 / / 3 / 4 / 5 / 6 ...但我无法在我的示例中使用它。

我的适配器:

public void onBindViewHolder(RestaurantsAdapter.RestaurantsViewHolder holder, int position) {
    // getting restaurant data for the row
    Restaurant restaurant = restaurant Items.get(position);

    holder.userName.setText(restaurant .getUserName());
    holder.date.setText(convertDate(restaurant .getDateTime())); //string dobiti u formatu, pretvoriti ga u localized i podijeliti na dva dijela
    holder.time.setText(convertTime(restaurant .getDateTime()));

    TextDrawable.IBuilder builder = TextDrawable.builder()
            .beginConfig()
            .withBorder(0)
            .toUpperCase()
            .endConfig()
            .roundRect(10);
    ColorGenerator generator = ColorGenerator.MATERIAL;
    int color = generator.getColor(restaurant.getUserId());
    TextDrawable textDrawable = builder.build(restaurant Items.get(position).getUserName().substring(0, 1), color);
    holder.thumbNail.setImageDrawable(textDrawable);

    Picasso.with(context)
            .load(AppConfig.URL_PROFILE_PHOTO + restaurant.getThumbnailUrl())
            .placeholder(textDrawable)
            .error(textDrawable)
            .transform(new RoundedTransform(12, 0))
            .fit()
            .centerCrop()
            .into(holder.thumbNail);
}

 private String convertDate(String time) {
    final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());

    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortDateFormat).toPattern(), Locale.getDefault());

    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

private String convertTime(String time) {
    final DateFormat shortTimeFormat = android.text.format.DateFormat.getTimeFormat(context.getApplicationContext());
    SimpleDateFormat timeFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat timeFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortTimeFormat).toPattern(), Locale.getDefault());

    java.util.Date date = null;

    try {
        date = timeFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return timeFormatConverted.format(date);
}

更新:

我尝试将此添加到我的解决方案中:

 private String convertDate(String time) {
    final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
    Calendar Now = Calendar.getInstance();
    Now.getDisplayName(Calendar.HOUR, Calendar.SHORT, Locale.getDefault());
    SimpleDateFormat dateFormatReceived = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    SimpleDateFormat dateFormatConverted = new SimpleDateFormat(((SimpleDateFormat) shortDateFormat).toPattern(), Locale.getDefault());
    dateFormatConverted.getDisplayName(Calendar.HOUR, Calendar.SHORT, Locale.getDefault());
    java.util.Date date = null;

    try {
        date = dateFormatReceived.parse(time);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return dateFormatConverted.format(date);
}

请尝试使用 getDisplayName(...) 方法

为了获得更多信息,您最好阅读 this 文档


已编辑

更充分的你可以这样试试:

int monthOfYear = Calendar.JULY; // 6
String monthName = new 
DateFormatSymbols(Locale.getDefault()).getShortMonths()[monthOfYear];

我想下面的方法会给你你想要的日期时间格式化程序。

public static DateTimeFormatter getLocalizedDateFormatter(Locale requestedLocale) {
    String formatPatternString = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
            FormatStyle.SHORT, null, 
            Chronology.ofLocale(requestedLocale), requestedLocale);
    // if not already showing month name, modify so it shows abbreviated month name
    if (! formatPatternString.contains("MMM")) {
        formatPatternString = formatPatternString.replaceAll("M+", "MMM");
    }
    return DateTimeFormatter.ofPattern(formatPatternString, requestedLocale);
}

测试:

    Locale[] locales = { Locale.US, Locale.FRANCE, Locale.GERMANY,
            Locale.forLanguageTag("da-DK"), Locale.forLanguageTag("sr-BA") };
    LocalDate today = LocalDate.now(ZoneId.of("Europe/Sarajevo"));
    for (Locale currentLocale : locales) {
        DateTimeFormatter ldf = getLocalizedDateFormatter(currentLocale);
        System.out.format(currentLocale, "%-33S%s%n", 
                currentLocale.getDisplayName(), today.format(ldf));
    }

输出:

ENGLISH (UNITED STATES)          Dec/24/17
FRENCH (FRANCE)                  24/déc./17
GERMAN (GERMANY)                 24.Dez.17
DANSK (DANMARK)                  24-dec.-17
SERBIAN (BOSNIA AND HERZEGOVINA) 17-дец-24

JSR-310 也称为 java.time

您尝试使用早已过时且出了名的麻烦 类 DateFormatSimpleDateFormat。相反,我建议您养成使用 JSR-310、现代 Java 日期和时间 API 的习惯。所以我用上面的方法来做。

我不认为这是问题的一部分,但为了完整起见,按如下方式解析日期时间字符串。您从我的 getLocalizedDateFormatter 获得的格式化程序可用于格式化 LocalDateTime 和除 LocalDate.

之外的许多其他日期时间类型
    LocalDateTime ldt = LocalDateTime.parse("2017-12-24 22:51:34",
            DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"));
    String formattedDate = ldt.format(getLocalizedDateFormatter(Locale.UK));

问题:我可以在 Android 上使用 JSR-310 吗?

是的,你可以。它只需要至少 Java 6.

  • 在 Java 8 及更高版本中内置了新的 API。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,新 类 的 backport(ThreeTen for JSR 310)。
  • 在 Android,使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。

在后两种情况下,请确保将适当版本的向后移植库添加到您的项目中,使用下面的链接,并导入我使用的 类 来自 org.threeten.bporg.threeten.bp.format.

链接