Created
December 22, 2016 20:34
-
-
Save JohannMG/dd38883b121f4043f9b5ab147fad3c03 to your computer and use it in GitHub Desktop.
Date extension to get pretty Apple-mail like labels.
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
| import Foundation | |
| extension Date { | |
| func formattedMessageDate() -> String { | |
| let startOfToday = Calendar.current.startOfDay(for: Date()) | |
| let startOfDate = Calendar.current.startOfDay(for: self) | |
| let components = (Calendar.current as NSCalendar).components([NSCalendar.Unit.day, NSCalendar.Unit.hour], from: startOfDate, to: startOfToday, options: NSCalendar.Options(rawValue: 0)) | |
| if components.day! > 7 { | |
| return self.shortDate | |
| } else if components.day == 0 { | |
| return self.time | |
| } else if components.day == 1 { | |
| return "Yesterday" | |
| } else { | |
| return self.weekdayString() | |
| } | |
| } | |
| var shortDate: String { | |
| let dateFormatter = DateFormatter() | |
| dateFormatter.dateStyle = .short | |
| return dateFormatter.string(from: self) | |
| } | |
| var weekday: String { | |
| let weekdayFormatter = DateFormatter() | |
| weekdayFormatter.dateFormat = "EEEE" | |
| return weekdayFormatter.string(from: self) | |
| } | |
| func weekdayString() -> String { | |
| let weekdayFormatter = DateFormatter() | |
| weekdayFormatter.dateFormat = "EEEE" | |
| return weekdayFormatter.string(from: self) | |
| } | |
| var time: String { | |
| let weekdayFormatter = DateFormatter() | |
| weekdayFormatter.dateFormat = "HH:mm" | |
| weekdayFormatter.timeStyle = .short | |
| return weekdayFormatter.string(from: self) | |
| } | |
| static func testDate(_ daysAgo: Int) -> Date { | |
| let testDate = "2016-01-17 17:39:48" | |
| let dateFormatter = DateFormatter() | |
| dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss" | |
| if let date = dateFormatter.date(from: testDate) { | |
| var components = (Calendar.current as NSCalendar).components([NSCalendar.Unit.year, | |
| NSCalendar.Unit.day, | |
| NSCalendar.Unit.hour], | |
| from: date) | |
| guard let day = components.day else { | |
| return Date() | |
| } | |
| components.day = day - daysAgo | |
| let yesterday = Calendar.current.date(from: components) | |
| return yesterday ?? Date() | |
| } | |
| return Date() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment