如何在 java 中以不同的语言(西班牙语)打印从 sql 日期开始的月份?
How to print month from sql date in different language (Spanish) in java?
我可以用这几行代码用英文打印月份
但是我怎样才能用西班牙语打印呢?我在(简单日期格式)
的区域设置中没有找到任何西班牙语
它使用的DateFormat
和java.util.Date
已经过时了。您应该(如果可能)使用更新的 JSR-310 java date/time 库和格式化程序,如 DateTimeFormatter
。下面是使用西班牙语(西班牙)语言环境的最近 推荐 JSR-310 Java date/time 库和最近 DateTimeFormatter
的示例代码:
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern("MMM d, yyyy h:mm a", new Locale("es", "ES"));
String formattedDateTime = dateTimeFormatter.format(dateTime);
如果您出于某种原因不得不使用旧的过时库,那么您可以使用SimpleDateFormat(String pattern, Locale locale)
。以下是在西班牙语(西班牙)语言环境中使用 DateFormat
的示例代码:
Date dateTime = new Date();
DateFormat date = new SimpleDateFormat(
"MMM d, yyyy h:mm a", new Locale("es", "ES"));
String formattedDateTime = date.format(dateTime);
JDBC 4.2 和 java.time
Locale desiredLanguage = Locale.forLanguageTag("es");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM", desiredLanguage);
OffsetDateTime dateTime = yourResultSet.getObject("your_database_column", OffsetDateTime.class);
String monthString = dateTime.format(monthFormatter);
或者在某个特定时区打印,因为月份不会在所有时区的同一时间点发生变化:
ZonedDateTime zdt = dateTime.atZoneSameInstant(ZoneId.of("Europe/Madrid"));
String monthString = zdt.format(monthFormatter);
避免使用 SimpleDateFormat
您提到的 SimpleDateFormat
class 是出了名的麻烦且早已过时。不要使用它。 java.time,现代 Java 日期和时间 API,使用起来更方便。
Link
Oracle tutorial: Date Time 解释如何使用 java.time。
我可以用这几行代码用英文打印月份 但是我怎样才能用西班牙语打印呢?我在(简单日期格式)
的区域设置中没有找到任何西班牙语它使用的DateFormat
和java.util.Date
已经过时了。您应该(如果可能)使用更新的 JSR-310 java date/time 库和格式化程序,如 DateTimeFormatter
。下面是使用西班牙语(西班牙)语言环境的最近 推荐 JSR-310 Java date/time 库和最近 DateTimeFormatter
的示例代码:
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern("MMM d, yyyy h:mm a", new Locale("es", "ES"));
String formattedDateTime = dateTimeFormatter.format(dateTime);
如果您出于某种原因不得不使用旧的过时库,那么您可以使用SimpleDateFormat(String pattern, Locale locale)
。以下是在西班牙语(西班牙)语言环境中使用 DateFormat
的示例代码:
Date dateTime = new Date();
DateFormat date = new SimpleDateFormat(
"MMM d, yyyy h:mm a", new Locale("es", "ES"));
String formattedDateTime = date.format(dateTime);
JDBC 4.2 和 java.time
Locale desiredLanguage = Locale.forLanguageTag("es");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM", desiredLanguage);
OffsetDateTime dateTime = yourResultSet.getObject("your_database_column", OffsetDateTime.class);
String monthString = dateTime.format(monthFormatter);
或者在某个特定时区打印,因为月份不会在所有时区的同一时间点发生变化:
ZonedDateTime zdt = dateTime.atZoneSameInstant(ZoneId.of("Europe/Madrid"));
String monthString = zdt.format(monthFormatter);
避免使用 SimpleDateFormat
您提到的 SimpleDateFormat
class 是出了名的麻烦且早已过时。不要使用它。 java.time,现代 Java 日期和时间 API,使用起来更方便。
Link
Oracle tutorial: Date Time 解释如何使用 java.time。