Using a NumberFormatter within a DateFormatter

Viewed 238

I'm attempting to format my Date() to look like Saturday, June 12th • 5PM - 12PM. I've been able to solve the majority of this with the following DateFormatter():

var date_formatter: DateFormatter {
    let formatter = DateFormatter()
    formatter.dateFormat = "EEEE, MMMM d • HHa - HHa"
    return formatter
}

Which results in Saturday, June 12 • 5PM - 12PM

The challenge I'm having is understanding how to add the ordinal suffix (i.e. 12 -> 12th). I've seen a bit on the NumberFormatter(), but am not entirely sure how to integrate the two.

EDIT: Ended up having to create two formats for the 5PM - 12PM logic.

This looks like:

var start_time_formatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE, MMMM d • HHa -"
        return formatter
    }

    var end_time_formatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "HHa"
        return formatter
    }

with the following to display it in a view:

Text("\(self.create_event_vm.start_time, formatter: self.start_time_formatter) \(self.create_event_vm.end_time, formatter: self.end_time_formatter)")

I understand this is a bit funky and could use some refactoring, but I'm hoping to get the desired effect, test, then refactor.

3 Answers

First for the day suffix you can create below function

func getDaySuffix(from date: Date) -> String {  
    switch Calendar.current.component(.day, from: date) {
    case 1, 21, 31: return "st"
    case 2, 22: return "nd"
    case 3, 23: return "rd"
    default: return "th"
    }
}

and combine with your codes :

let startDate = Date()
let endDate = Calendar.current.date(byAdding: .hour, value: 5, to: startDate)!

var startTimeFormatter: DateFormatter {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "EEEE, MMMM d'\(getDaySuffix(from: startDate))' • ha - "
    return formatter
}

var endTimeFormatter: DateFormatter {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "ha"
    return formatter
}

let startDateResult = startTimeFormatter.string(from: startDate) // "Thursday, June 18th • 2AM - "
let endDateResult = endTimeFormatter.string(from: endDate) // "7AM"
let finalResult = startDateResult + endDateResult // "Thursday, June 18th • 2AM - 7AM"

First a helpful extension Int+Ordinal.swift:

extension Int {

    /// `Int` ordinal suffix
    enum Ordinal: String {

        /// Suffix for numbers ending in `1` except 11
        case st = "st"

        /// Suffix for numbers snding in `2` except 12
        case nd = "nd"

        /// Suffix for numbers ending in `3` except 13
        case rd = "rd"

        /// Suffix otherwise 
        case th = "th"
    }

    /// Get `Ordinal` from `Int` `self`
    var ordinal: Ordinal {
        var mod = self % 100
        if mod == 11 || mod == 12 || mod == 13 {
            return .th
        } else {
            mod = mod % 10
            if mod == 1 {
                return .st
            } else if mod == 2 {
                return .nd
            } else if mod == 3 {
                return .rd
            } else {
                return .th
            }
        }
    }
}

Then using this extension and DateFormatter:

func string(from startDate: Date, to endDate: Date) -> String {
    let formatter = DateFormatter()

    // weekdayMonth
    formatter.dateFormat = "EEEE, MMMM"
    let weekdayMonth = formatter.string(from: startDate)

    // day
    formatter.dateFormat = "d"
    var day = formatter.string(from: startDate)
    if let dayValue = Int(day) {
        day += dayValue.ordinal.rawValue
    }

    // timeFrom
    formatter.dateFormat = "ha"
    let timeFrom = formatter.string(from: startDate)

    // timeTo
    let timeTo = formatter.string(from: endDate)

    return "\(weekdayMonth) \(day) • \(timeFrom) - \(timeTo)"
}

Running it:

let dateString = string(from: Date(), to: Date().addingTimeInterval(3600 * 4))
print(dateString) // "Wednesday, June 17th • 11PM - 3AM"

Though I guess in this example you don't want it running into the next day! :)

You are going through the wrong path. What you need is to create a DateInterval and use its DateIntervalFormatter to display it to the user. Note that 12PM it is already another day so your date interval representation is wrong:

let dateA = DateComponents(calendar: .current, year: 2020, month: 6, day: 12, hour: 17, minute: 0).date!
let dateB = DateComponents(calendar: .current, year: 2020, month: 6, day: 13, hour: 0, minute: 0).date!
let di = DateInterval(start: dateA, end: dateB)
let dif = DateIntervalFormatter()
dif.dateTemplate = "EEEEMMMMdh"
dif.string(from: di)   // "Friday, June 12, 5 PM – Saturday, June 13, 12 AM"
Related