-
dateFormat으로 날짜를 파싱할때 에러!Android📱/삽질 기록... 2022. 10. 3. 17:23
프로젝트를 진행하면서 datePicker를 사용해서 날짜를 입력받는 기능을 구현하던 중
Your date pattern requires either a Locale, or your own custom localizations
라는 에러를 만나게 되었다...!!
구글링을 해보았지만 SimpleDateFormat에 대한 설명 만나와서...
나는 date4j라는 라이브러리를 이용했기에 코드를 보면서 직접 문제를 해결해보았다.
Date4j란
Java's Date Classes Must Die.
라는 슬로건을 걸고 John O'Hanley라는 분이 만든 날짜를 파싱 해주는 라이브러리이다.
DatePicker를 이용할 때 SimpleDateFormat을 사용하면 날짜가 오차가 생기거나 이상한 날짜가 생기는 현상이 발생해서
찾고 그 후로 사용 중인 라이브러리다.
홈페이지 : https://johanley.github.io/date4j/index.html
가볍고 간단한 라이브러리라서 홈페이지를 보면 대충 어떻게 사용하는 건지 다알 수 있으니
문제 해결을 한 코드를 확인해보려 한다.
우선 에러가 난 부분은
val dateFormat = dateTime.format("YYYY/MM/DD hh:mm::ss a")여기 부분이었다.
메시지에 쓰여있는 거처럼 YYYY/MM/DD hh:mm:ss a라는 포맷에 문제가 있다고 판단
그래서 코드를 따라가 보았다.
친절한 안드로이드 스튜디오 씨의 안내를 받아 가보면
String format(DateTime aDateTime){ fEscapedRanges = new ArrayList<EscapedRange>(); fInterpretedRanges = new ArrayList<InterpretedRange>(); findEscapedRanges(); interpretInput(aDateTime); return produceFinalOutput(); }여기서 interpreInput에 문제가 있고,
private void interpretInput(DateTime aDateTime){ String format = fFormat; for(String token : TOKENS){ Pattern pattern = Pattern.compile(token); Matcher matcher = pattern.matcher(format); while(matcher.find()){ InterpretedRange interpretedRange = new InterpretedRange(); interpretedRange.Start = matcher.start(); interpretedRange.End = matcher.end() - 1; if(! isInEscapedRange(interpretedRange)){ interpretedRange.Text = interpretThe(matcher.group(), aDateTime); fInterpretedRanges.add(interpretedRange); } } format = format.replace(token, withCharDenotingAlreadyInterpreted(token)); } }여기서 interpreThe()에서
else if (a.equals(aCurrentToken)){ int hour = aDateTime.getHour(); result = amPmIndicator(hour); }이 부분의
private String amPmIndicator(Integer aHour){ String result = ""; if(aHour != null){ if(fCustomLocalization != null){ result = lookupCustomAmPmFor(aHour); } else if (fLocale != null) { result = lookupAmPmFor(aHour); } else { throw new IllegalArgumentException( "Your date pattern requires either a Locale, or your own custom localizations for text:" + Util.quote(fFormat) ) ; } } return result; }여기서 aHour은 null이 아니지만 fCustemLocalization, fLocale 둘 다 null이라서 에러가 난다고 알려주었다.
그래서 a를 빼보니 잘 됨....
하지만 내가 원한것은 AM, PM이기에 a를 넣어야해서
fLocale이나 fCustomLocalization을 추가해주기 위해서
dateTime.format("YYYY/MM/DD hh:mm:ss a", Locale.ENGLISH)이렇게 Loacale을 추가해주니 문제 해결!
PM, AM을 얻고 싶었기 때문에 ENGLISH로 해주었다!
'Android📱 > 삽질 기록...' 카테고리의 다른 글
Gson, Retrofit2 - Enum Class 쓰는 법 (Kotlin, Android) (0) 2023.03.10 Retrofit DELETE Body 추가하기 (0) 2023.03.02 Jetpack Compose Navigation으로 URL 보낼때 오류Navigation destination that matches request NavDeepLinkRequest (0) 2022.10.11 [Android] 팀 프로젝트 Splash Activity 버그 개선기 feat. ViewTreeObserver (0) 2022.09.27 [android] 자잘한 삽질 기록...Conflicting overloads 에러 (0) 2022.05.14