728x90
개발을 하면서 어떠한 정보의 시작일과 종료일 표시를 해야할 때가 있다. 대부분은 시작일 및 종료일을 각각 시간날짜 데이터를 받아 SimpleDateFormat을 사용해서 원하는 형태(yyyy-MM-dd, yyyy.MM.dd)로 표현한다.
// 20221225
val format1 = SimpleDateFormat("yyyyMMdd")
// 20221225
val format2 = SimpleDateFormat("yyyy.MM.dd")
만약 여기서 아래와 같은 조건이 추가된 유틸 함수를 한번 만들어 보았다.
- 시작일과 종료일의 년도가 같을 경우
- 종료일의 년도는 yyyy에서 앞에 두개 yy를 제거(2022 -> 22)
- 시작일과 종료일의 년도가 다를 경우
- 시작일, 종료일 모두 년도 표시
- 시작일과 종료일이 같으면 하나만 표현
- 값이 빈 값이면 그 값은 표현하지 않음
먼저 서버로 부터 받은 시작일, 종료일 데이터와 데이터의 DateFormat를 매개변수로 받을 수 있는 함수를 정의한다.
fun getInfoDate(
startDateInfo: Pair<String, String>,
endDateInfo: Pair<String, String>
): String {
}
아래와 같이 매개변수 데이터형인 Pair<String, String>에서 first는 시작일, 종료일, second는 각각 Date 포맷 형태를 넣는다.
val startDateInfo = Pair(serverStartDate, "yyyyMMdd")
val endDateInfo = Pair(serverStartDate, "yyyyMMdd")
다음으로는 시작일 종료일 년도의 차이에 따라 다른 yyyy.MM.dd와 yy.MM.dd 날짜 포맷을 선언해준다.
val startDateFormatAndDifferYearEndDate = SimpleDateFormat("yyyy.MM.dd")
val sameYearEndDateFormat = SimpleDateFormat("yy.MM.dd")
표현할 날짜 포맷도 만들었으니 제일 중요한 시작일 년도와 종료일 년도를 비교할 수 있도록 년도를 추출하는 로직을 만들어 본다.
년도를 추출하기 위해서 StringDate -> Date로 컨버팅하는 함수를 아래와 같이 만들어 준다.
fun convertDateTime(dateTime: String?): Date {
if(dateTime.isNullOrEmpty()) return Date()
val format = SimpleDateFormat("yyyyMMddHHmmss", Locale.KOREA)
val tz = TimeZone.getTimeZone("Asia/Seoul")
format.timeZone = tz
return try {
format.parse(dateTime) ?: Date()
} catch (e: Exception) {
Date()
}
}
그리고 이를 시작일과 종료일을 매개변수에 넣어서 년도를 추출한다.
val startDateYear = yearFormat.format(Utils.convertDateTime(startDateInfo.first))
val endDateYear = yearFormat.format(Utils.convertDateTime(endDateInfo.first))
if (startDateYear != endDateYear) {
// 시작년도 종료년도가 다를 경우
} else {
// 시작년도 종료년도가 같을 경우
}
이제 조건에 따라 UI에 표현할 데이터를 만들어준다.
val startDateFormat = SimpleDateFormat(startDateInfo.second)
val endDateFormat = SimpleDateFormat(endDateInfo.second)
val start: String
val end: String
if (startDateYear != endDateYear) {
// 시작년도 종료년도가 다름
start = try { startDateFormatAndDifferYearEndDate.format(startDateFormat.parse(startDateInfo.first)) } catch (e: Exception) { "" }
end = try { startDateFormatAndDifferYearEndDate.format(endDateFormat.parse(endDateInfo.first)) } catch (e: Exception) { "" }
} else {
start = try { startDateFormatAndDifferYearEndDate.format(startDateFormat.parse(startDateInfo.first)) } catch (e: Exception) { "" }
end = try { sameYearEndDateFormat.format(endDateFormat.parse(endDateInfo.first)) } catch (e: Exception) { "" }
}
return when {
start == end -> end
start.isEmpty() -> end
end.isEmpty() -> start
else -> "$start~$end"
}
이렇게 하면 위에서 언급한 4가지 조건을 만족하는 데이터를 만들 수 있다. 실제 프로젝트에서 만들어서 사용 중이라 뿌듯하다.
전체코드
fun getInfoDate(startDateInfo: Pair<String, String>, endDateInfo: Pair<String, String>): String {
val yearFormat = SimpleDateFormat("yyyy")
val startDateFormatAndDifferYearEndDate = SimpleDateFormat("yyyy.MM.dd")
val sameYearEndDateFormat = SimpleDateFormat("yy.MM.dd")
val startDateYear = yearFormat.format(Utils.convertDateTime(startDateInfo.first))
val endDateYear = yearFormat.format(Utils.convertDateTime(endDateInfo.first))
val startDateFormat = SimpleDateFormat(startDateInfo.second)
val endDateFormat = SimpleDateFormat(endDateInfo.second)
val start: String
val end: String
if (startDateYear != endDateYear) {
// 시작년도 종료년도가 다름
start = try { startDateFormatAndDifferYearEndDate.format(startDateFormat.parse(startDateInfo.first)) } catch (e: Exception) { "" }
end = try { startDateFormatAndDifferYearEndDate.format(endDateFormat.parse(endDateInfo.first)) } catch (e: Exception) { "" }
} else {
start = try { startDateFormatAndDifferYearEndDate.format(startDateFormat.parse(startDateInfo.first)) } catch (e: Exception) { "" }
end = try { sameYearEndDateFormat.format(endDateFormat.parse(endDateInfo.first)) } catch (e: Exception) { "" }
}
return when {
start == end -> end
start.isEmpty() -> end
end.isEmpty() -> start
else -> "$start~$end"
}
}
'개발 이모저모' 카테고리의 다른 글
[안드로이드] 귀찮니즘이 만들어 준 contains() 함수 응용 (0) | 2022.12.20 |
---|---|
카카오 주소 및 키워드 api를 활용한 주소 검색 서비스 제작 (0) | 2021.11.16 |
지도에 중복 위경도 마커를 찍어보자 (0) | 2021.11.16 |
SharedPreference를 이용한 최근 검색어 리스트 만들기 (0) | 2021.11.16 |
HTTP 통신 로그 이쁘장하게 찍어보기 (0) | 2021.11.16 |