如何将月份的语言更改为西班牙语?

问题描述

我从API这样接收日期:

2020-09-10T20:00:00.000Z

当我转换此日期时,它显示SEPTEMBER 10,2020 8:00 p. m.

我需要用西班牙语显示月份,例如SeptiembreSep

解决方法

您可以尝试这样的操作(它以10 de septiembre de 2020 20:00的格式返回日期):

val format: DateFormat = DateFormat.getDateTimeInstance(
    DateFormat.LONG,// date format
    DateFormat.SHORT,// time format
    Locale("es","ES") // Spanish Locale
)

val dateTime = "2020-09-10T20:00:00.000Z"
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale("es","ES"))
val date: Date = simpleDateFormat.parse(dateTime)!! // without validation

println(format.format(date)) // it prints `10 de septiembre de 2020 20:00`
,

我建议您使用modern java.time日期时间API和相应的格式API(软件包java.time.format)来完成此操作,而不要使用过时且容易出错的{{1 }}日期时间API和java.util。从 Trail: Date Time 了解有关现代日期时间API的更多信息。如果您的Android API级别仍不兼容Java8,请检查How to use ThreeTenABP in Android ProjectJava 8+ APIs available through desugaring

使用现代的日期时间API进行以下操作:

SimpleDateFormat

输出:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // The given date-time string
        String strDateTime = "2020-09-10T20:00:00.000Z";

        // Parse the given date-time string into OffsetDateTime
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime);

        // Define the formatter for output in a custom pattern and in Spanish Locale
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd,uuuu hh:mm a",new Locale("es","ES"));

        // Print instant using the defined formatter
        String formatted = formatter.format(odt);
        System.out.println(formatted);
    }
}

如果您仍要使用旧的日期时间和格式API,可以按以下步骤进行操作:

septiembre 10,2020 08:00 p. m.

输出:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        // The given date-time string
        String strDateTime = "2020-09-10T20:00:00.000Z";

        // Define the formatter to parse the input string
        SimpleDateFormat inputFormatter = new SimpleDateFormat("yyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        // Parse the given date-time string into java.util.Date
        Date date = inputFormatter.parse(strDateTime);
        
        // Define the formatter for output in a custom pattern and in Spanish Locale
        SimpleDateFormat outputFormatter = new SimpleDateFormat("MMMM dd,yyyy hh:mm a","ES"));

        // Print instant using the defined formatter
        String formatted = outputFormatter.format(date);
        System.out.println(formatted);
    }
}