Archive

[iOS] UTC to localTime 🗺

lgvv 2022. 2. 19. 03:12

✅ 이번시간은 UTC 시간을 Local 시간으로 바꾸는 과정을 알아보자.

 

🍎 애플 문서 참고

https://developer.apple.com/documentation/foundation/timezone/

 

Apple Developer Documentation

 

developer.apple.com

 

 

✅ UTC to local Time

import Foundation
import UIKit

extension Date {
    private static func utcToLocal(_ dateStr: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm:ss" 
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        
        if let date = dateFormatter.date(from: dateStr) {
            dateFormatter.timeZone = TimeZone.current // 현재 지역의 타임존
            
            let loccation = TimeZone.current.identifier
            
            if loccation == "Asia/Seoul" {
                dateFormatter.dateFormat = "a hh:mm" // Asia/Seoul "오전 06:00"
            } else {
                dateFormatter.dateFormat = "hh:mm a" // Golbal "06:00 PM"
            }

            return dateFormatter.string(from: date)
        }
        return nil
    }
    
    public static func convertLocalTime(initHour hour: Int) -> String {
        let hourStr = "\(hour):00:00"
        return Date.utcToLocal(hourStr) ?? ""
    }
}

 

 

 

'Archive' 카테고리의 다른 글

[iOS] UserDefault Property Wrapper  (0) 2022.02.24
[iOS] Swift 전처리문 #if DEBUG 사용하기  (0) 2022.02.19