티스토리 뷰

하다보면 날짜에 관련된 코드를 다룰 때가 많은데 

생각보다 편리해서 올려봅니다. 

import Foundation
import UIKit

extension Date { // swift 5 부터 제공되는 함수 라고 합니다
    func isEqual(to date: Date, toGranularity component: Calendar.Component, in calendar: Calendar = .current) -> Bool {
        calendar.isDate(self, equalTo: date, toGranularity: component)
    }
    func isInSameYear(as date: Date) -> Bool { isEqual(to: date, toGranularity: .year) }
    func isInSameMonth(as date: Date) -> Bool { isEqual(to: date, toGranularity: .month) }
    func isInSameWeek(as date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }
    func isInSameDay(as date: Date) -> Bool { Calendar.current.isDate(self, inSameDayAs: date) }
    var isInThisYear:  Bool { isInSameYear(as: Date()) }
    var isInThisMonth: Bool { isInSameMonth(as: Date()) }
    var isInThisWeek:  Bool { isInSameWeek(as: Date()) }
    var isInYesterday: Bool { Calendar.current.isDateInYesterday(self) }
    var isInToday:     Bool { Calendar.current.isDateInToday(self) }
    var isInTomorrow:  Bool { Calendar.current.isDateInTomorrow(self) }
    var isInTheFuture: Bool { self > Date() }
    var isInThePast:   Bool { self < Date() }
}

사용방법은 

var date : Date // 원하시는 날짜 넣으시면 됩니다. 
date.isInToday // 이런식으로 이용하시면 됩니다.

isEqual : 같은 날짜인가요(시간까지 동일한 경우)

isInSameYear : 같은 년도 인가요

isInSameMonth : 같은 달 인가요

isInSameWeek : 같은 주 인가요

isInSameDay : 같은 날 인가요(해당 당일인 경우)

isInThisYear : 이번 년도 인가요

isInThisMonth : 이번 달인가요

isInThisWeek : 이번주인가요

isInYesterday : 어제인가요

isInToday : 오늘인가요

isInTomorrow : 내일인가요

isInTheFuture : 미래인가요

isInThePast : 과거인가요

 

참고 사이트 

https://stackoverflow.com/questions/43663622/is-a-date-in-same-week-month-year-of-another-date-in-swift

 

Is a date in same week, month, year of another date in swift

What is the best way to know if a date is in the same week (or year or month) as another, preferably with an extension, and solely using Swift? As an example, in Objective-C I have - (BOOL)isSame...

stackoverflow.com

 

'iOS개발 > Swift 기본' 카테고리의 다른 글

Swift Date <-> String 타입 변경하기  (0) 2022.10.14
Swift UIColor hex 주고 받기  (0) 2022.09.23
Swift 내 앱 버전 알아보기  (0) 2022.09.23
Swift 모델명 알아내기  (0) 2022.09.23
Swift UIView 테두리 둥글게 하기  (0) 2022.09.23
댓글