Files
sodalive-ios/SodaLive/Sources/Extensions/StringExtension.swift
T
Yu Sung 2f8331f2ff 라이브 시작시간 UTC 적용
라이브 상세와 수정 화면에서 UTC 기준 시간을 표시한다.
날짜 표기는 OS 언어 설정의 기본 포맷을 사용한다.
2026-01-05 11:36:26 +09:00

107 lines
3.5 KiB
Swift

//
// StringExtension.swift
// SodaLive
//
// Created by klaus on 2022/06/03.
//
import Foundation
extension Optional where Wrapped == String {
func isNullOrBlank() -> Bool {
return self == nil || self!.trimmingCharacters(in: .whitespaces).isEmpty
}
}
extension String {
func convertDateFormat(from: String, to: String, locale: Locale? = nil) -> String {
let fromFormatter = DateFormatter()
fromFormatter.dateFormat = from
fromFormatter.timeZone = TimeZone(identifier: TimeZone.current.identifier)
if let locale = locale {
fromFormatter.locale = locale
}
if let date = fromFormatter.date(from: self) {
return date.convertDateFormat(dateFormat: to)
} else {
return self
}
}
func substring(from: Int, to: Int) -> String {
guard from < count, to >= 0, to - from >= 0 else {
return ""
}
// Index 값 획득
let startIndex = index(self.startIndex, offsetBy: from)
let endIndex = index(self.startIndex, offsetBy: to + 1) // '+1'이 있는 이유: endIndex는 문자열의 마지막 그 다음을 가리키기 때문
// 파싱
return String(self[startIndex ..< endIndex])
// 출처 - https://ios-development.tistory.com/379
}
func formatCurrency(currencyCode: String, locale: Locale = .current) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = locale
formatter.currencyCode = currencyCode
let dec = NSDecimalNumber(string: self)
return formatter.string(from: dec) ?? "\(currencyCode) \(self)"
}
func parseUtcIsoLocalDateTime() -> [String: String] {
// 1. 서버에서 내려온 포맷: "yyyy-MM-dd'T'HH:mm:ss"
let utcFormatter = DateFormatter()
utcFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
utcFormatter.locale = Locale.current
utcFormatter.timeZone = TimeZone(abbreviation: "UTC")
// 2. 문자열 → Date 객체
guard let date = utcFormatter.date(from: self) else {
return [:] // 파싱 실패 시 빈 딕셔너리 반환
}
// 3~6. 출력용 Formatter (로컬 시간 기준)
let localFormatter = DateFormatter()
localFormatter.locale = Locale.autoupdatingCurrent
localFormatter.timeZone = TimeZone.current
// 3. 월 (1~12)
localFormatter.dateFormat = "M"
let month = localFormatter.string(from: date)
// 4. 일 (1~31)
localFormatter.dateFormat = "d"
let day = localFormatter.string(from: date)
// 5. 요일 (예: "Mon", "목")
localFormatter.dateFormat = "E"
let dayOfWeek = localFormatter.string(from: date)
// 6. 시간 (예: "AM 05:00")
localFormatter.dateFormat = "a hh:mm"
let time = localFormatter.string(from: date)
return [
"month": month,
"day": day,
"dayOfWeek": dayOfWeek,
"time": time
]
}
func parseUtcIsoDate() -> Date? {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter.date(from: self)
}
}