LoginSignup
5
3

More than 5 years have passed since last update.

SimpleDateFormatのparseでコケるときに確認すること

Last updated at Posted at 2017-07-13

Javaで Thu, 13 Jul 2017 18:00:15 +0900 こういう形式の文字列をDate型に変換したいとき、ありませんか?

こんな感じで

public class Main {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
        System.out.println(sdf.parse("Thu, 13 Jul 2017 18:00:15 +0900"));
    }
}

SimpleDateFormatのparseメソッドを使うと実現できる…といろんな記事に書いているのですが、実際に実行すると

Exception in thread "main" java.text.ParseException: Unparseable date: "Thu, 13 Jul 2017 18:00:15 +0900"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at Main.main(Main.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

こんな感じの例外が発生してしまいます。

そこでこのように書き換えます。

public class Main {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
        System.out.println(sdf.parse("Thu, 13 Jul 2017 18:00:15 +0900"));
    }
}

3行目、SimpleDateFormatのコンストラクタの第二引数にLocaleを渡しています。

これでちゃんと Thu Jul 13 18:00:15 JST 2017 という出力が得られます。

原因

原因についてはこの記事で触れましたので、もし興味がありましたらご覧ください。

SimpleDateFormatのparseでコケるときに確認すること #60 - ゆるふわ技術日誌

5
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3