java - 如何在 Java 中设置尊重用户操作系统设置的日期和时间格式

我在 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/

相关文章:

google-apps-script - 单元格处于事件状态时突出显示整行

html - 为什么 Visual Studio 格式文档工具将标题标签放在两行上?

string - 为什么不使用 %v 打印 int 和 string

ruby - 如何格式化 BigDecimal 以仅显示所需数量的十进制数字?

ruby - 在rails应用程序中生成pdf时如何用Prawn定义行高?

formatting - 突出显示重复值

jquery - 如何自定义 Eclipse 的关于 jQuery 代码的格式化程序

php - Aptana 自动格式化

r - 在 knitr 上设置全局千位分隔符

sql-server - 漂亮的 T-SQL 打印机?