关于java:格式化日期根据区域设置,然后获取日期部分

Format Date according to locale and then get the date part

我要实现的是将格式为yyyyMMdd的日期转换为区域设置格式,即yyyy/MM/dddd/MM/yyyy等。我对时间部分不感兴趣,我只需要日期。

函数将获取字符串日期并以区域设置格式返回字符串日期。

我现在拥有的是:

1
2
dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
convertedDate = dateFormat.parse("20120521");

此后我所尝试的一切要么返回一个包含时间和gmt等的长字符串,要么返回我传递给函数的相同字符串。


听起来您已经对解析部分进行了排序——这与格式化部分完全分离。

对于格式化,我怀疑您需要:

1
2
DateFormat localeFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
String text = localeFormat.format(convertedDate);

…用SHORTMEDIUMLONGFULL做实验,看看哪一个最能满足你的需要,但我怀疑它会是SHORTMEDIUM

(您可以省略getDateInstance的第二个参数,它将使用默认的区域设置,但我个人建议将其明确地包括进来,以便于理解。)


以下是您问题的答案:如何在Java中用区域设置日期?

一个例子:

1
2
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);

另外,如果你需要在日期方面做很多事情,可以考虑使用Joda:Java,没有时间就可以获取日期


要使用内置类型的日期格式

1
DateFormat df = DateFormat.getDateInstance(DateFormat.Short, Locale.getDefault()));

按照JavaDocs

Use getDateInstance to get the normal date format for that country.
There are other static factory methods available. Use getTimeInstance
to get the time format for that country. Use getDateTimeInstance to
get a date and time format. You can pass in different options to these
factory methods to control the length of the result; from SHORT to
MEDIUM to LONG to FULL. The exact result depends on the locale, but
generally:

SHORT is completely numeric, such as 12.13.52 or 3:30pm MEDIUM is
longer, such as Jan 12, 1952 LONG is longer, such as January 12, 1952
or 3:30:32pm FULL is pretty completely specified, such as Tuesday,
April 12, 1952 AD or 3:30:42pm PST.