Format date and time but exclude "today date" in Swift?

50 Views Asked by At

My code:

let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = .short
        dateFormatter.dateStyle = .short
        dateFormatter.locale = .current
        lblDateTime.text = dateFormatter.string(from: date)

The problem is I need dateFormatter.dateStyle = .none for today date. How to resolve it correctly? Is it possible to avoid manual date calculations to determine "today date"?

2

There are 2 best solutions below

0
vadian On BEST ANSWER

You can check if the given date is in today, Calendar provides an appropriate API

let isDateInToday = Calendar.current.isDateInToday(date)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.dateStyle = isDateInToday ? .none : .short
dateFormatter.locale = .current
lblDateTime.text = dateFormatter.string(from: date)

If you can live with a four digit year and non-padded day and month, this is an alternative

let isDateInToday = Calendar.current.isDateInToday(date)
lblDateTime.text = date.formatted(date: isDateInToday ? .omitted : .numeric, time: .shortened)
0
SchmidtFx On

From iOS 8.0 you could use the isDateInToday(_:) method from Calendar.

Code Example

let dateFormatter = DateFormatter()

...

dateFormatter.dateStyle = Calendar.current.isDateInToday(date) ? .none : .short

You'll find further informations for this method also in the Apple documentation: https://developer.apple.com/documentation/foundation/calendar/2293243-isdateintoday