99 lines
3.2 KiB
Swift
99 lines
3.2 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
|
|
]
|
|
}
|
|
}
|