20231004 TIL 숫자변환 함수코드

이성진·2023년 10월 4일
0

TIL

목록 보기
46/95

Android Kotlin 유튜브 검색 API로 동영상 정보 처리하기

유튜브 검색 API를 사용하여 검색된 동영상의 정보를 적절하게 표시하기 위한 코드를 소개합니다.

1. 시간 변환

동영상의 업로드 시간을 사용자 친화적으로 표시합니다.

companion object {
        const val MIN = 60
        const val HOUR = 60 * 60
        const val DAY = 60 * 60 * 24
        const val MONTH = 60 * 60 * 24 * 30
        const val YEAR = 60 * 60 * 24 * 365
    } 
fun convertPublishedDate(publishedDate: String): String {

      val result = StringBuilder()

      try {
          val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
          simpleDateFormat.timeZone = TimeZone.getTimeZone("GMT")

          val convertedPublishedTime =
              simpleDateFormat.parse(publishedDate)?.time ?: 0L
          val currentTime = System.currentTimeMillis()

          val diff = (currentTime - convertedPublishedTime) / 1000

          when {
              diff < MIN -> {
                  result.append(diff).append("초전")
              }
              diff < HOUR -> {
                  result.append(diff / MIN).append("분전")
              }
              diff < DAY -> {
                  result.append(diff / HOUR).append("시간전")
              }
              diff < MONTH -> {
                  result.append(diff / DAY).append("일전")
              }
              diff < YEAR -> {
                  result.append(diff / MONTH).append("달전")
              }
              else -> {
                  result.append(diff / YEAR).append("년전")
              }
          }

      } catch (e: ParseException) {
          return ""
      }

      return result.toString()
  }

2. 조회수 변환

정수 형태의 조회수를 천 회 , 만 회 같은 형태로 변환합니다.

fun convertViewCount(viewCount: String): String {

     val result = StringBuilder()

     try {
         val longViewCount = viewCount.replace(".", "").replace(",", "").toLong()

         when {
             longViewCount < 1000 -> {
                 result.append(longViewCount / 100).append("백회")
             }
             longViewCount < 10_000 -> {
                 result.append(longViewCount / 1_000).append("천회")
             }
             longViewCount < 100_000_000 -> {
                 result.append(longViewCount / 10_000).append("만회")
             }
             else -> {
                 result.append(longViewCount / 100_000_000).append("억회")
             }
         }

     } catch (e: NumberFormatException) {
         return result.toString()
     }

     return result.toString()
 }

3. 영상 길이 변환

ISO 8601 포맷의 영상 길이를 시:분:초 형태로 변환 합니다.

fun convertDurationToHHMMSS(duration: String): String {

     val regexMap: HashMap<String, String> = HashMap()

     val regex2two = "(?<=[^\\d])(\\d)(?=[^\\d])"
     val two = "0$1"

     regexMap["PT(\\d\\d)S"] = "00:$1"
     regexMap["PT(\\d\\d)M"] = "$1:00"
     regexMap["PT(\\d\\d)H"] = "$1:00:00"
     regexMap["PT(\\d\\d)M(\\d\\d)S"] = "$1:$2"
     regexMap["PT(\\d\\d)H(\\d\\d)S"] = "$1:00:$2"
     regexMap["PT(\\d\\d)H(\\d\\d)M"] = "$1:$2:00"
     regexMap["PT(\\d\\d)H(\\d\\d)M(\\d\\d)S"] = "$1:$2:$3"

     val d: String = duration.replace(
         regex2two.toRegex(), two
     )

     getRegex(regexMap, d)?.let {
         return d.replace(it.toRegex(), regexMap[it]!!)
     } ?: return "00:00"

 }

이렇게 유튜브 API를 통해 얻은 정보를 사용자 친화적으로 변환하는 코드를 살펴보았습니다. Kotlin을 활용하여 간결하고 효율적인 변환 코드를 작성할 수 있습니다.

profile
2023.08 ~ Android Kotlin 공부

0개의 댓글