Last active
February 7, 2020 08:47
-
-
Save yycking/e3aa2f78c231d308f027e6b37b2a8393 to your computer and use it in GitHub Desktop.
Swift DateFormat like apple mail
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 Cocoa | |
extension Calendar { | |
func isDateIn7days(from date: Date) -> Bool { | |
let date1 = self.startOfDay(for: Date()) | |
let date2 = self.startOfDay(for: date) | |
let days = (date1 - date2).day ?? 0 | |
return days <= 8 && days > 0 | |
} | |
} | |
extension Date { | |
static func - (lhs: Date, rhs: Date) -> DateComponents { | |
let calendar = Calendar.current | |
return calendar.dateComponents([.day], from: rhs, to: lhs) | |
} | |
var formattedRelativeString: String { | |
let calendar = Calendar.current | |
let dateFormatter = DateFormatter() | |
switch self { | |
case let date where calendar.isDateInToday(date): | |
dateFormatter.timeStyle = .short | |
case let date where calendar.isDateInYesterday(date): | |
dateFormatter.dateStyle = .short | |
dateFormatter.doesRelativeDateFormatting = true | |
case let date where calendar.isDateIn7days(from: date): | |
dateFormatter.dateFormat = "EEEE" | |
default: | |
dateFormatter.dateStyle = .short | |
} | |
return dateFormatter.string(from: self) | |
} | |
} | |
let calendar = Calendar.current | |
let today = Date() | |
Array(0...10).reversed().forEach { value in | |
let date = calendar.date(byAdding: .day, value: -value, to: today)! | |
print( date.formattedRelativeString) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment