모바일앱/iOS
iOS 날짜정보를 불러와서 비교하기
GeekCode
2022. 5. 18. 09:50
반응형
현재 날짜 불러오기
let current = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let currentDate = formatter.string(from: current).components(separatedBy: "-")
숫자형으로 만들어 사용하기
let current = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
// Date형태에서 String형태로 전환
let currentDate = formatter.string(from: current).components(separatedBy: "-")
// String형태에서 Int 형태로 전환
let currentDateArray = currentDate.map({ (value: String) -> Int in return Int(value)!})
print("이번 연도 정보",currentDateArray.first, type(of: currentDateArray.first))
// 이번 연도 정보 2022 Int
현재 날짜를 배열로 저장 / 사용 / 비교하기
// userDefault Get 리턴
static func dateInfoUserDefaultsGet(key: String) -> [String]? {
if let result = UserDefaults.standard.object(forKey: key) as? [String] else {
print("저장한 어레이가 없음")
return nil
}
print("어레이정보 Get 완료")
return result
}
// 사용하기
if let array = dateInfoUserDefaultsGet(key: Constants.didShareMapUrl) {
// 코드입력
}
// 저장하기
var array : [String] = []
array.append(contentsOf: didShareMapUrlArray)
monthlyUserDefaultsSet(key:"userDefaultKey", value: array)
static func dateInfoUserDefaultsSet(key: String, value: [String]) -> Void {
UserDefaults.standard.set(value as [String], forKey: key)
UserDefaults.standard.synchronize()
print("어레이정보 Set 완료")
}
// 날짜 비교하기
//현재 날짜 가져오기
let current = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
// Date형태에서 String형태로 전환
let currentDate = formatter.string(from: current).components(separatedBy: "-")
// 비교를 위해 Int로 전환
let currentDateArray = currentDate.map({ (value: String) -> Int in return Int(value)!})
// 저장된 날짜정보 가져오기
if let array = dateInfoUserDefaultsGet(key: Constants.didShareMapUrl) {
// 비교를 위해 Int로 전환
let didLoadyArray = array.map({ (value: String) -> Int in return Int(value)!})
// 현재 날짜가 저장된 날짜보다 이후인지 비교
if (didLoadyArray.first! != currentDateArray.first!) || ((didLoadyArray.first! == currentDateArray.first!) && (didLoadyArray.last! != currentDateArray.last!)) {
//코드입력
}
}
반응형