Skip to content

Instantly share code, notes, and snippets.

@aheze
Last active March 27, 2020 20:20
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 aheze/cc72eb7d7474c20e69e1d2529f43a1a7 to your computer and use it in GitHub Desktop.
Save aheze/cc72eb7d7474c20e69e1d2529f43a1a7 to your computer and use it in GitHub Desktop.
func convertDateToReadableString(dateToConvert: Date) -> String {
/// Make a date formatter object. This will take care converting Date objects to String objects and vice versa.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMddyy" /// This is a pretty good format that will yield something like "January 1, 2020"
let todaysDate = Date() /// When you initialize a Date object like this, the Date will be the current date.
let todaysDateAsString = dateFormatter.string(from: todaysDate)
let yesterday = todaysDate.subtract(days: 1)
let yesterdaysDateAsString = dateFormatter.string(from: yesterday!)
let oneWeekAgo = todaysDate.subtract(days: 7)
let dayBeforeYesterday = yesterday?.subtract(days: 1)
let range = oneWeekAgo!...dayBeforeYesterday!
let stringDate = dateFormatter.string(from: dateToConvert)
/// This will be the date that you want to convert as a String
/// Now, we do some simple if/else checks.
if stringDate == todaysDateAsString {
return "Today"
} else if stringDate == yesterdaysDateAsString {
return "Yesterday"
} else {
if range.contains(dateToConvert) {
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: dateToConvert)
} else {
dateFormatter.dateFormat = "MMMM d',' yyyy"
return dateFormatter.string(from: dateToConvert)
}
}
}
extension Date {
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