Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Created September 20, 2022 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/53c36df6de4d9756b6f35b530d55e10e to your computer and use it in GitHub Desktop.
Save TuenTuenna/53c36df6de4d9756b6f35b530d55e10e to your computer and use it in GitHub Desktop.
Swift 시간 비교하기
extension Date {

    static func -(recent: Date, previous: Date) -> (month: Int?, day: Int?, hour: Int?, minute: Int?, second: Int?) {
        let day = Calendar.current.dateComponents([.day], from: previous, to: recent).day
        let month = Calendar.current.dateComponents([.month], from: previous, to: recent).month
        let hour = Calendar.current.dateComponents([.hour], from: previous, to: recent).hour
        let minute = Calendar.current.dateComponents([.minute], from: previous, to: recent).minute
        let second = Calendar.current.dateComponents([.second], from: previous, to: recent).second

        return (month: month, day: day, hour: hour, minute: minute, second: second)
    }

}

let interval = Date() - updatedDate
print(interval.day)
print(interval.month)
print(interval.hour)

usage

let calendar = Calendar.current
            
let second = Calendar.current.dateComponents([.second], from: storedDate, to: Date()).second

let minute = Calendar.current.dateComponents([.minute], from: storedDate, to: Date()).minute

print(#fileID, #function, #line, "시간 차이 : second: \(second)")

print(#fileID, #function, #line, "시간 차이 : minute: \(minute)")

출처 https://stackoverflow.com/questions/50950092/calculating-the-difference-between-two-dates-in-swift/54751685#54751685

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment