2016-10-13 5 views
1

SimpleDateFormat에 문제가 있습니다. 안드로이드 에뮬레이터에서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.ENGLISH 또는 Locale.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 

출력 될 것입니다 : 당신이 java.util.Date이를 변환해야하는 경우

2016-10-24T19:31

, 당신은 org.threeten.bp.DateTimeUtils 클래스를 사용할 수 있습니다. 그러나 이것을 변환하는 데 사용할 시간대를 알아야합니다. 나는 "UTC"를 사용하고 아래의 예에서 :

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

다른 영역으로 변경하려면, 당신은 할 수 있습니다 : API가 형식 Continent/CityIANA timezones names (항상 사용

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

하는 것으로 예 : 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()); 
관련 문제