Xia*_*gua 5 java time parsing simpledateformat
DateFormat formatter = new SimpleDateFormat("hh:mmaa");
formatter.parse("01:20pm")
Run Code Online (Sandbox Code Playgroud)
我试图以01:20 pm的格式解析时间.如果我运行上面的代码,我会得到以下异常:
java.text.ParseException: Unparseable date: "01:20pm"
at java.text.DateFormat.parse(DateFormat.java:366)
Run Code Online (Sandbox Code Playgroud)
至于我在SimpleDateFormat构造函数中放置的格式,我没有看到任何错误.这里出了什么问题?
您的系统区域设置无法识别AM/PM.使用Locale那样做.就像是,
DateFormat formatter = new SimpleDateFormat("hh:mmaa", Locale.US);
Run Code Online (Sandbox Code Playgroud)
或者,在Java 8+中,使用新的java.timeAPI
LocalTime lt = LocalTime.parse("01:20pm",
DateTimeFormatter.ofPattern("hh:mmaa", Locale.US));
Run Code Online (Sandbox Code Playgroud)