Search code examples
swiftdatedateformatter

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


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)