본문 바로가기

UIKIT/UIDate

날짜 형식 변환

📌 날짜 형식 변환 (2025-2-11 → 2월 11일 2025년)

🔷 TMDB API를 통해 받아오는 데이터 중 released_date의 날자 형식을 변경

{
  "page": 1,
  "results": [
    {
     ...
      "popularity": 396.136,
      "release_date": "2025-01-15",
      ...
    },
    ...

 

movie.releaseDate는 "2025-2-11" 형식의 String이므로,

 1️⃣ 먼저 Date 타입으로 변환한 후
 2️⃣ 원하는 형식으로 다시 String으로 변환

 

 

🚀 해결 방법

🔹 Step 1: String → Date 변환

  • 현재 날짜 형식 "2025-2-11"은 "yyyy-M-d" 형태
  • 따라서 DateFormatter를 사용하여 Date 타입으로 변환

🔹 Step 2: Date → String 변환

  • "2월 11일 2025년" 형식으로 만들려면 "M월 d일 yyyy년"을 사용

 

🔧 최적화된 변환 함수

func formatDateString(_ dateString: String) -> String {
    let inputFormatter = DateFormatter()
    inputFormatter.dateFormat = "yyyy-M-d" // ✅ 원본 형식 (2025-2-11)
    inputFormatter.locale = Locale(identifier: "ko_KR") // ✅ 한국어 로케일 설정

    guard let date = inputFormatter.date(from: dateString) else { return dateString } // 변환 실패 시 원본 반환

    let outputFormatter = DateFormatter()
    outputFormatter.dateFormat = "M월 d일 yyyy년" // ✅ 원하는 출력 형식
    outputFormatter.locale = Locale(identifier: "ko_KR")

    return outputFormatter.string(from: date) // ✅ 최종 변환된 문자열 반환
}

 

 

🚀 적용 예제

🔹 configureCollectionView(with:)에서 적용

func configureCollectionView(with movie: MovieResult) {
    titleLabel.text = movie.title
    releasedDateLabel.text = formatDateString(movie.releaseDate) // ✅ 날짜 변환 적용

    let score = (movie.voteAverage)
    if score != 0 {
        scoreLabel.configure(with: Int(score) * 10)
    } else {
        scoreLabel.configure(with: 100)
    }

    let posterPath = movie.posterPath
    guard let url = URL(string: "https://image.tmdb.org/t/p/w500/\(posterPath)") else { return }
    
    posterImageView.sd_setImage(with: url, completed: nil)
}