Programming Language/Kotlin

[Kotlin] Compare two formatted Date Strings

개발왕 금골드 2023. 6. 3. 08:21
반응형

목차

  • Import Library
  • 날짜 데이터 생성
  • 날짜 비교
  • 예제 결과
  • 결론

 

Import Library

import java.text.SimpleDateFormat
import java.time.Duration
import java.time.LocalDateTime
import java.util.*

 

날짜 데이터 생성

// 현재 시간 가져오기

val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault())
val date = try {
    val millis = Calendar.getInstance(TimeZone.getTimeZone("UTC")).timeInMillis
    format.format(Date(millis))
} catch (e: Exception) {
    ""
}
val currentDate = LocalDateTime.parse(date)
// 비교할 날짜 가져오기

val someDate = LocalDateTime.parse("2023-05-01T12:12:12.111")

 

날짜 비교

// 두 개의 Formatted Strings 비교

val betweenDays = Duration.between(measurementDate, currentDate).toDays()
val betweenHours = Duration.between(measurementDate, currentDate).toHours()
val betweenMinutes = Duration.between(measurementDate, currentDate).toMinutes()

Log.d("compare date", "day : $betweenDays")

 

예제 결과

"day : 29"

 

결론

두 개의 Formatted Date는 비교가 가능하다. 단, 두 형식은 같은 형식이어야 하며, 만약 String 안에 parsing이 불가능한 문자열이 들어 있다면, DateTimeParseException이 발생한다.

반응형