2016-10-13 10 views
1

SimpleDateFormatに問題があります。 Androidのエミュレータでjava.text.ParseException:解析できない日付:java.text.DateFormat.parse(DateFormat.java:579)

SimpleDateFormat dtfmt=new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.getDefault()); 
Date dt=dtfmt.parse(deptdt); 

正常に動作しますが、携帯電話に、私はこのエラーを持っている:

W/System.err: java.text.ParseException: Unparseable date: "24 Oct 2016 7:31 pm" (at offset 3) W/System.err: at java.text.DateFormat.parse(DateFormat.java:579)

任意のソリューション?

答えて

1

deptdtには、英語の月のように見えるOctが含まれています。 Locale.getDefault()は、おそらく英語以外のロケールを指定します。 Locale.ENGLISHLocale.USことによってそれを置き換え :

SimpleDateFormat dtfmt=new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.ENGLISH); 
Date dt=dtfmt.parse(deptdt); 
0

を(Oct)携帯電話のデフォルトロケールが英語ではないので、それはおそらく発生し、あなたの入力の月名です。 (この古いAPIがlots of problemsdesign issuesを持っているとして)、あなたはThreeTen Backport、大きなバックポートを使用することができ、直接SimpleDateFormatでの作業の代わりに

SimpleDateFormat dtfmt = new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.ENGLISH); 
Date dt = dtfmt.parse("24 Oct 2016 7:31 pm"); 

ソリューションは、明示的に英語ロケールを使用することですJava 8の新しい日付/時刻クラス。 Androidで使用するには、ThreeTenABP(詳しくはhereの使用方法)が必要です。

主なクラスはorg.threeten.bp.LocalDateTime(入力に日付と時刻のフィールドがあるので最適です)とorg.threeten.bp.format.DateTimeFormatter(入力を解析する)です。私もそれが英語の月名を解析することを確認するjava.util.Localeクラスを使用して、org.threeten.bp.format.DateTimeFormatterBuilder(デフォルトはPMあるとして、それは大文字小文字を区別します)、それはpmを解析することを確認する:

DateTimeFormatter fmt = new DateTimeFormatterBuilder() 
    // case insensitive to parse "pm" 
    .parseCaseInsensitive() 
    // pattern 
    .appendPattern("dd MMM yyyy h:mm a") 
    // use English locale to parse month name (Oct) 
    .toFormatter(Locale.ENGLISH); 
// parse input 
LocalDateTime dt = LocalDateTime.parse("24 Oct 2016 7:31 pm", fmt); 
System.out.println(dt); // 2016-10-24T19:31 

出力は次のようになります。

2016-10-24T19:31

あなたはjava.util.Dateにこれを変換する必要がある場合は、org.threeten.bp.DateTimeUtilsクラスを使用することができます。しかし、これを変換するために使用するタイムゾーンを知る必要もあります。以下の例では、私は「UTC」を使用しています:

Date date = DateTimeUtils.toDate(dt.atZone(ZoneOffset.UTC).toInstant()); 

を別のゾーンに変更するには、行うことができます:

Date date = DateTimeUtils.toDate(dt.atZone(ZoneId.of("Europe/London")).toInstant()); 

注意をAPIがフォーマットContinent/Cityで常に(IANA timezones namesを使用していること例えば、America/Sao_PauloまたはEurope/Berlin)。 ambiguous and not standardであるため、3文字の略語(CSTまたはなど)は使用しないでください。各地域に適したタイムゾーンを見つけるには、ZoneId.getAvailableZoneIds()メソッドを使用して、ユースケースに最適なタイムゾーンを確認してください。

PS:上記の最後の例(dt.atZone(ZoneId.of("Europe/London")))は、ロンドン時間帯の日付/時刻2016-10-24T19:31を作成します。しかし、あなたが望むものがUTCで2016-10-24T19:31であれば、別のタイムゾーンに変換してください。

Date date = DateTimeUtils.toDate(dt 
    // first convert it to UTC 
    .toInstant(ZoneOffset.UTC) 
    // then convert to LondonTimezone 
    .atZone(ZoneId.of("Europe/London")).toInstant()); 
関連する問題