iOS iOS - 1 year ago 73
Swift Question

ios - How to display date read "Today, 14 April"?

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download