我在 Windows 7 机器上运行我的 Java 应用程序,我的区域设置设置为将日期格式设置为 YYYY-mm-dd 并将时间格式设置为 HH:mm:ss(例如“2011-06-20 07:50: 28 英寸)。但是当我使用 DateFormat.getDateTimeInstance().format
来格式化我的日期时,我没有看到“20-Jun-2011 7:50:28 AM”。我需要怎么做才能按照我的客户设置操作系统来显示日期的方式来格式化日期?
我的代码如下所示:
File selGameLastTurnFile = selectedGame.getLastTurn ().getTurnFile ();
Date selGameModifiedDate = new Date (selGameLastTurnFile.lastModified());
if (selectedGame.isYourTurn ()) {
gameInfo = Messages.getFormattedString ("WhoseTurnIsIt.Prompt.PlayTurn", //$NON-NLS-1$
FileHelper.getFileName (selGameLastTurnFile),
DateFormat.getDateTimeInstance().format(selGameModifiedDate));
} else {
gameInfo = Messages.getFormattedString ("WhoseTurnIsIt.Prompt.SentTurn", //$NON-NLS-1$
selGameLastTurnFile.getName (),
DateFormat.getDateTimeInstance().format(selGameModifiedDate));
}
Messages.getFormattedString
调用使用 MessageFormat
将日期放入如下所示的句子中:
Play the turn 'QB Nat vs Ian 008' (received 20-Jun-2011 7:50:28 AM)
但是我的操作系统设置设置为如上所述格式化日期,我希望看到这个:
Play the turn 'QB Nat vs Ian 008' (received 2011-06-20 07:50:28)
我搜索了这里和其他 Java 编程网站,但找不到答案,但这似乎是一件显而易见的事情,我觉得我错过了一些明显的东西。
最佳答案
首先你必须告诉Java你的系统LOCALE是什么样的。
Check Java System.
String locale = System.getProperty("user.language")
And then format the date accordinly (SimpleDateFormat)
SimpleDateFormat(String pattern, Locale locale)
请参阅实用的 Java 代码以获取工作示例...
String systemLocale = System.getProperty("user.language");
String s;
Locale locale;
locale = new Locale(systemLocale );
s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
System.out.println(s);
// system locale is PT outputs 16/Jul/2011
locale = new Locale("us");
s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
System.out.println(s);
// outputs Jul 16, 2011
locale = new Locale("fr");
s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
System.out.println(s);
// outputs 16 juil. 2011
https://stackoverflow.com/questions/6711925/