某些区域设置中的AM / PM符号不符合预期

时间:2014-05-26 07:26:35

标签: java locale simpledateformat

我发现这篇帖子有点解释了我的一半问题。这就是为什么我的AM符号不符合我的预期。 Unable to parse DateTime-string with AM/PM marker

SimpleDateFormat sdfBefore = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.US);
// I tried format with 2 [a] as well , MM/dd/yyyy hh:mm:ss aa
//SimpleDateFormat sdfAfter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

System.out.println("Debug: test6 = "+sdfBefore.format(System.currentTimeMillis()));
System.out.println("Debug: test7 = "+sdfBefore.parse("05/26/2014 06:57:07 a.m."));
System.out.println("Debug: test8 = "+sdfBefore.parse("05/26/2014 06:57:08 A.M."));
System.out.println("Debug: test9 = "+sdfBefore.parse("05/26/2014 06:57:09 AM"));

这是我的结果:

Debug: test6 = 05/26/2014 07:30:01 a.m.
Debug: test7 = Mon May 26 06:57:07 GMT 2014
Debug: test8 = Mon May 26 06:57:08 GMT 2014
Error: java.text.ParseException: invalid Date syntax in "05/26/2014 06:57:09 AM"

我到目前为止尝试过的语言环境:

German = vorm.
US/ENGLISH/<default>/Canada = a.m.
chinese = ? <--probably cause my sonsole doesn't support it

我在网上找到的每个例子都说英语/美国语言环境对于符号来说应该是正确的#34; AM&#34;和&#34; PM&#34;

有没有人注意到这里有什么问题?

1 个答案:

答案 0 :(得分:1)

好的,所以我发现了一种蛮力的方法来修复它,但如果有人知道它的根源是什么,我仍然会很高兴。

DateFormatSymbols sym = new DateFormatSymbols(Locale.US);
sym.setAmPmStrings(new String[] { "AM", "PM"});
SimpleDateFormat sdfBefore = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", sym);

System.out.println("Debug: test6 = "+sdfBefore.format(System.currentTimeMillis()));
System.out.println("Debug: test9 = "+sdfBefore.parse("05/26/2014 06:57:09 AM"));

结果:

Debug: test6 = 05/26/2014 07:47:44 AM
Debug: test9 = Mon May 26 06:57:09 GMT 2014