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

2024-02-21

我在 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));
}

The Messages.getFormattedString通话正在使用MessageFormat将日期放入句子中,如下所示:

进行“QB Nat vs Ian 008”回合(2011 年 6 月 20 日上午 7:50:28 收到)

然而,我的操作系统设置被设置为格式化日期,如上所述,我希望看到这一点:

进行“QB Nat vs Ian 008”回合(2011-06-20 07:50:28 收稿)

我在这里和其他 Java 编程网站上进行了搜索,但找不到答案,但这似乎是一件显而易见的事情,我觉得我错过了一些明显的事情。


首先,您必须告诉 Java 您的系统 LOCALE 是什么样的。

检查 Java 系统。 http://download.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties%28%29
String locale = System.getProperty("user.language")

然后相应地格式化日期(SimpleDateFormat) http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
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  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Java 中设置尊重用户操作系统设置的日期和时间格式 的相关文章

随机推荐