Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading