Search code examples
swiftxcodensdateformatterswift5

Formatting a Date and Time in Swift


I have this time format 2022-01-09T19:04:16 obtained from an API. I would like to show a readable time from this string and also, possibly the difference from given time and current time.

I cannot find a suitable format for this. Can someone please assist? I tried to substring the retrieved value as below, but, this is not what I want.

let str = "2022-01-09T19:04:16" print(str.suffix(8)) //prints 19:04:16


Solution

  • You can convert the String to Date and handle all operations that you would like to do with it.

    1. As the input format is not a standard one I assume that we are using UTC.
    2. If the input changes the function will throw an error without breaking most of your code.
    enum DateFormattingErrors: Error {
        case invalidFormat
    }
    
    func formatDate(_ from: String) throws -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
        guard let date = dateFormatter.date(from: from) else {
            throw DateFormattingErrors.invalidFormat
        }
        
        return date
    }
    
    func UTCFormattedDate(_ from: Date, withDate: Bool) -> String {
        let utcDateFormatter = DateFormatter()
        if withDate {
            utcDateFormatter.dateStyle = .medium
        }
        utcDateFormatter.timeStyle = .medium
        utcDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return utcDateFormatter.string(from: from)
    }
    
    do {
        let date = try formatDate("2022-01-09T19:04:16")
        print(Date().description)
        print(date.timeIntervalSinceNow) //Time difference between given date and current date
        print(UTCFormattedDate(date, withDate: false)) // Better representation of date
    } catch {
        print(error)
    }
    

    Output

    2022-01-10 10:09:03 +0000  //CurrentDate
    -54287.22359800339         //Time difference current and given
    7:04:16 PM                 //Formatted date