Reputation: 3626
I want to present some dates which reads
Yesterday, 13 April
Today, 14 April
Tomorrow, 15 April
Tuesday, 4 April
Wednesday 5 April
I tried
let date = Date(timeIntervalSince1970: value)
let dayFormatter = DateFormatter()
dayFormatter.dateStyle = .medium
dayFormatter.doesRelativeDateFormatting = true
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d MMMM"
whenLabel.text = dayFormatter.string(from: date) + ", " + dateFormatter.string(from: date)
It is working fine as expected if the date is today, but, for other dates, I get “Apr 5, 2017, 5 April”
How can I get ride of this issue?
Upvotes: 2
Views: 1138
Reputation: 1059
As Sulthan suggest I just come to know about this kind of code,
let mydate = Date()//my actual date need to display
let dateFormatter = DateFormatter()
if Calendar.current.isDateInToday(mydate) {
dateFormatter.dateFormat = "'Today,' d MMMM"
}
else if Calendar.current.isDateInYesterday(mydate) {
dateFormatter.dateFormat = "'Yesterday,' d MMMM"
}
else if Calendar.current.isDateInTomorrow(mydate) {
dateFormatter.dateFormat = "'Tomorrow,' d MMMM"
}
else{
dateFormatter.dateFormat = "EEEE, d MMMM"
}
Please update me if we have any better way. Thanks
Upvotes: 1
Reputation: 285220
Just for fun this is a solution which takes advantage of the localized relative date formatting.
It uses an extension of Calendar
which determines if a date is in yesterday, today or tomorrow:
extension Calendar {
func isDateInYesterdayTodayTomorrow(_ date: Date) -> Bool
{
return self.isDateInYesterday(date) || self.isDateInToday(date) || self.isDateInTomorrow(date)
}
}
func relativeDateString(for date: Date, locale : Locale = Locale.current) -> String
{
let dayFormatter = DateFormatter()
dayFormatter.locale = locale
if Calendar.current.isDateInYesterdayTodayTomorrow(date) {
dayFormatter.dateStyle = .medium
dayFormatter.doesRelativeDateFormatting = true
} else {
dayFormatter.dateFormat = "EEEE"
}
let relativeWeekday = dayFormatter.string(from: date)
let dateFormatter = DateFormatter()
dateFormatter.locale = locale
dateFormatter.dateFormat = "d MMMM"
return relativeWeekday + ", " + dateFormatter.string(from: date)
}
Upvotes: 1
Reputation: 130162
You will need two completely different formatters depending on whether the date is today or not. doesRelativeDateFormatting
won't help you with complex formatting.
Start by checking:
if Calendar.current.isDateInToday(date) {
// use "Today, " + "d MMMM" pattern
} else {
// use "EEEE" pattern + "d MMMM" pattern
}
Upvotes: 2