Last active
December 21, 2022 01:03
-
-
Save aheze/a744af49c8dad126bc653bc854a97a24 to your computer and use it in GitHub Desktop.
This file contains 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 convertDateToReadableString() -> String { | |
let todayString = "Today" | |
let yesterdayString = "Yesterday" | |
/// Initializing a Date object will always return the current date (including time) | |
let todaysDate = Date() | |
guard let yesterday = todaysDate.subtract(days: 1) else { return "2023" } | |
guard let oneWeekAgo = todaysDate.subtract(days: 7) else { return "2023" } | |
guard let dayBeforeYesterday = yesterday.subtract(days: 1) else { return "2023" } | |
/// This will be any date from one week ago to the day before yesterday | |
let recently = oneWeekAgo ... dayBeforeYesterday | |
/// convert the date into a string, if the date is before yesterday | |
let dateFormatter = DateFormatter() | |
/// If self (the date that you're comparing) is today | |
if Calendar.current.isDateInToday(self) { | |
return todayString | |
/// if self is yesterday | |
} else if Calendar.current.isDateInYesterday(self) { | |
return yesterdayString | |
/// if self is in between one week ago and the day before yesterday | |
} else if recently.contains(self) { | |
/// "EEEE" will display something like "Wednesday" (the weekday) | |
dateFormatter.dateFormat = "EEEE" | |
return dateFormatter.string(from: self) | |
/// self is before one week ago | |
} else { | |
/// displays the date as "January 1, 2020" | |
/// the ' ' marks indicate a character that you add (in our case, a comma) | |
dateFormatter.dateFormat = "MMMM d" | |
return dateFormatter.string(from: self) | |
} | |
} | |
func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? { | |
let comp = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds) | |
return Calendar.current.date(byAdding: comp, to: self) | |
} | |
func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? { | |
return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment