Java DateFormat.SHORT 与全年
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3608716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java DateFormat.SHORT with full year
提问by ManiSto
Is there any way to make DateFormatformat a date with a full year (eg. 12/12/2010), when using DateFormat.SHORTas the pattern? I have to format dates in both en_US and da_DK.
DateFormat当DateFormat.SHORT用作模式时,有什么方法可以使格式为一整年的日期(例如 12/12/2010)?我必须在 en_US 和 da_DK 中格式化日期。
I know I could use DateFormat.MEDIUM, but the date have to be formatted using only numbers and separators, and DateFormat.MEDIUMfor en_US produces something like 'Dec 12, 2010'.
我知道我可以使用DateFormat.MEDIUM,但必须仅使用数字和分隔符来格式化日期,并且DateFormat.MEDIUM对于 en_US 会产生类似“2010 年 12 月 12 日”的内容。
采纳答案by Bozho
If both formats are the same, then simply use:
如果两种格式相同,则只需使用:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
If they differ:
如果它们不同:
private static Map<Locale, String> formats = new HashMap<Locale, String>();
static {
formats.put(new Locale("en_US"), "dd/MM/yyyy");
formats.put(new Locale("da_DK"), "dd.MM.yyyy");
}
And then instead of using DateFormat.getDateInstance(..)use
然后而不是使用DateFormat.getDateInstance(..)使用
new SimpleDateFormat(formats.get(locale)).format(..);
回答by Rijk
java.time
时间
You can use the java.timeclasses that supplant the old date-time classes. Instead of DateFormat, use a DateTimeFormatterderived from a DateTimeFormatterBuilder.
您可以使用取代旧日期时间类的java.time类。而不是DateFormat使用DateTimeFormatter从 a 派生的 a DateTimeFormatterBuilder。
DateTimeFormatterBuildercan provide a pattern that can be used with DateTimeFormatter. Using String.replaceyou can insert yyyyinstead of yyin the FormatStyle.SHORTdate pattern:
DateTimeFormatterBuilder可以提供可以与DateTimeFormatter. 使用String.replace您可以插入yyyy而不是yy在FormatStyle.SHORT日期模式中:
String pattern =
DateTimeFormatterBuilder
.getLocalizedDateTimePattern
( FormatStyle.SHORT
, null
, IsoChronology.INSTANCE
, locale
);
pattern = pattern.replace("yy", "yyyy");
DateTimeFormatter dtf =
DateTimeFormatter.ofPattern(pattern);
回答by NatashaK
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
if (df instanceof SimpleDateFormat) {
SimpleDateFormat sdf = (SimpleDateFormat) df;
// To show Locale specific short date expression with full year
String pattern = sdf.toPattern().replaceAll("y+", "yyyy");
sdf.applyPattern(pattern);
return sdf.format(cal.getTime());
}

