SimpleDateFormat and locale based format string

2019-01-02 17:55发布

I'm trying to format a date in Java in different ways based on the given locale. For instance I want English users to see "Nov 1, 2009" (formatted by "MMM d, yyyy") and Norwegian users to see "1. nov. 2009" ("d. MMM. yyyy").

The month part works OK if I add the locale to the SimpleDateFormat constructor, but what about the rest?

I was hoping I could add format strings paired with locales to SimpleDateFormat, but I can't find any way to do this. Is it possible or do I need to let my code check the locale and add the corresponding format string?

9条回答
浮光初槿花落
2楼-- · 2019-01-02 18:44
String text = new SimpleDateFormat("E, MMM d, yyyy").format(date);
查看更多
刘海飞了
3楼-- · 2019-01-02 18:48

This will display the date according to user's current locale:

import java.text.DateFormat;    
import java.util.Date;

Date date = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
String myDate = df.format(date);

Dec 31, 1969 7:00:02 PM

DateFormat.getDateInstance() 

Dec 31, 1969

查看更多
低头抚发
4楼-- · 2019-01-02 18:50

Java 8 Style for a given date

LocalDate today = LocalDate.of(1982, Month.AUGUST, 31);
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.ENGLISH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.FRENCH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.JAPANESE)));
查看更多
登录 后发表回答