java.text.ParseException:无法解析的日期:"01:19 PM"

Kos*_*asC 6 java simpledateformat

我只想解析一个简单的时间!这是我的代码:

   String s = "01:19 PM";
        Date time = null;
        DateFormat  parseFormat = new SimpleDateFormat("hh:mm aa");
        try {
            time = parseFormat.parse(s);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

java.text.ParseException: Unparseable date: "01:19 PM"
    at java.text.DateFormat.parse(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

Nic*_*zyk 5

这有效:

  public static void main(String[] args) throws Exception {
   String s = "01:19 PM";
   Date time = null;
   DateFormat parseFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
   System.out.println(time = parseFormat.parse(s));
  }
Run Code Online (Sandbox Code Playgroud)

.OUPUTS:

  Thu Jan 01 13:19:00 KST 1970
Run Code Online (Sandbox Code Playgroud)


icz*_*cza 5

模式字母a是Am/pm标记,但它是特定于区域设置的.显然AM并且PM在英语语言环境中有效,但它们在匈牙利语语言环境中无效.

得到的ParseException原因是您设置了非英语语言环境,并且您的语言环境PM无效.

// This is OK, English locale, "PM" is valid in English
Locale.setDefault(Locale.forLanguageTag("en"));
new SimpleDateFormat("hh:mm aa").parse("01:19 PM");

// This will throw Exception, Hungarian locale, "PM" is invalid in Hungarian
Locale.setDefault(Locale.forLanguageTag("hu"));
new SimpleDateFormat("hh:mm aa").parse("01:19 PM");
Run Code Online (Sandbox Code Playgroud)

要解决此问题,Locale可以在构造函数中指定:

// No matter what is the default locale, this will work:
new SimpleDateFormat("hh:mm aa", Locale.US).parse("01:19 PM");
Run Code Online (Sandbox Code Playgroud)