Files
sodalive-ios/SodaLive/Sources/Extensions/StringExtension.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
]
}
}