无法使用 AM/PM 标记解析日期时间字符串 [英] Unable to parse DateTime-string with AM/PM marker
问题描述
我要格式化的字符串如下所示:字符串日期时间 = "9/1/10 11:34:35 AM"
The string I want to format looks like this: String datetime = "9/1/10 11:34:35 AM"
SimpleDateFormat 的以下模式有效:
Following pattern for SimpleDateFormat works:
SimpleDateFormat sdf = SimpleDateFormat("M/d/yy h:mm:ss");
Date d = sdf.parse(datetime);
System.out.println(d);
Output> [Wed Sep 01 11:34:35 CEST 2010]
但是我也需要解析 AM/PM 标记,当我将它添加到模式时,我收到一个异常.
However I need to parse the AM/PM marker as well, and when I add that to the pattern I receive an exception.
不起作用的模式:
SimpleDateFormat sdf = SimpleDateFormat("M/d/yy h:mm:ss a");
我也试过这个,但有同样的例外:
I have tried with this also with same exception:
SimpleDateFormat sdf = SimpleDateFormat("M/d/yy h:mm:ss aa");
异常:
java.text.ParseException: Unparseable date: "9/1/10 11:34:35 AM"
我浏览了 http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#text 但似乎找不到我做错的地方.
I have looked through the API at http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#text but canät seem to find where I do wrong.
有什么建议吗?
推荐答案
一种可能性是您的默认 Locale
具有不同的 AM/PM 符号.在构建日期格式时,您应该始终提供 Locale
,除非您确实想使用系统默认的 Locale
,例如:
One possibility is that your default Locale
has different symbols for AM/PM. When constructing a date format you should always supply a Locale
unless you really want to use the system's default Locale
, e.g.:
SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm:ss a", Locale.US)
这篇关于无法使用 AM/PM 标记解析日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!