Last active
September 26, 2018 15:14
-
-
Save descorp/4d72ebafaf876ce8149a49e5a2e86432 to your computer and use it in GitHub Desktop.
Date Extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSComparisonResult)compareDatesWith:(NSDate*)otherDate { | |
NSCalendar* calendar = [NSCalendar currentCalendar]; | |
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; | |
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:self]; | |
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:otherDate]; | |
NSInteger comparison = [comp1 year] * 10000 + [comp1 month] * 100 + [comp1 day] - | |
([comp2 year] * 10000 + [comp2 month] * 100 + [comp2 day]); | |
return comparison > 0 ? NSOrderedDescending : comparison < 0 ? NSOrderedAscending : NSOrderedSame; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Date { | |
func toString(format: String) -> String { | |
let formatter = DateFormatter() | |
formatter.dateFormat = format | |
return formatter.string(from: self) | |
} | |
var isToday: Bool { | |
return compareDate(Date()) == .orderedSame | |
} | |
var isYesterday: Bool { | |
let yesterday = Date().addDay(-1) | |
return compareDate(yesterday) == .orderedSame | |
} | |
var toUserFriendlyFormat: String { | |
switch self { | |
case let date where date.isToday: | |
return "Today" | |
case let date where date.isYesterday: | |
return "Yesterday" | |
default: | |
return self.toString(format: "dd MMMM") | |
} | |
} | |
private func addDay(_ diff: Int) -> Date { | |
let calendar = Calendar.current | |
return calendar.date(byAdding: .day, value: diff, to: self)! | |
} | |
private func compareDate(_ other: Date) -> ComparisonResult { | |
let calendar = Calendar.current | |
let components: [Calendar.Component] = [.year, .month, .day] | |
let lhs = calendar.dateComponents(Set(components), from: self) | |
let rhs = calendar.dateComponents(Set(components), from: other) | |
let diff = (lhs.year! - rhs.year!) * 10000 + (lhs.month! - rhs.month!) * 100 + lhs.day! - rhs.day! | |
return diff > 0 ? .orderedAscending : diff == 0 ? .orderedSame : .orderedDescending | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment