Skip to content

Instantly share code, notes, and snippets.

@rungxanh1995
Created April 12, 2023 17:27
Show Gist options
  • Save rungxanh1995/c4d001f056cec67ef465cd0bcb117384 to your computer and use it in GitHub Desktop.
Save rungxanh1995/c4d001f056cec67ef465cd0bcb117384 to your computer and use it in GitHub Desktop.
Relative "Today" string instead of value from RelativeDateTimeFormatter
// This is what I have in my project for relativeDueDate string
struct TaskItem {
...
var relativeDueDate: String {
let formatter = RelativeDateTimeFormatter()
formatter.dateTimeStyle = .named
return formatter.localizedString(for: dueDate, relativeTo: .now).capitalizingFirstLetter()
}
}
// My extension of Date
// Date.swift
extension Date {
/// User’s current calendar.
private var calendar: Calendar { Calendar.current }
/// Check if date is within today
var isWithinToday: Bool { calendar.isDateInToday(self) }
}
// So you can combine these two
// and could have a guard check in your convertToRelativeFormat() -> String method like this
func convertToRelativeFormat() -> String {
guard self.isWithinToday == false else { return "Today" } // or localized string for "Today"
// then go with the rest of your existing logic here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment