iosswiftdatensdatecomponents

How to convert a DateComponents-object to a localized string, such as "08:40 PM", without specifying year, month, and day?


I have a "time" (hours and minutes) stored in a DateComponents-object, and I like to convert that to a localized string format such that 08:40 PM, och 20:40, etc.

I now how to display a Date-object (NSDAte) in this way, but to convert 20:40 to a Date I must pretend I know the Year, Month, and Day.

Question: Is it possible to to convert a DateComponents-object to a localized string, such as "08:40 PM", by using TimeZone- and Locale-object, but without specifying the Year, Month, and Day?


Solution

  • You can just get todays components and add the desired time to it. You will also need to specify a calendar:

    extension Date {
        var year: Int { Calendar.current.component(.year, from: self) }
        var month: Int { Calendar.current.component(.month, from: self) }
        var day: Int { Calendar.current.component(.day, from: self) }
    }
    

    extension DateComponents {
        var todaysDateFromTimeComponents: Date? {
            let today =  Date()
            return DateComponents(calendar: .current,
                                  year: today.year,
                                  month: today.month,
                                  day: today.day,
                                  hour: hour,
                                  minute: minute)
            .date
        }
    }
    

    let date = DateComponents(hour: 20, minute: 40).todaysDateFromTimeComponents // "Feb 1, 2017, 8:40 PM"
    


    If you want to display “date information in a given time zone” you should use DateFormatter to format your date.

    extension DateFormatter {
        convenience init(timeStyle: DateFormatter.Style) {
            self.init()
            self.timeStyle = timeStyle
        }
    }
    

    extension Date {
        static let shortTimeFormatter = DateFormatter(timeStyle: .short)
        func shortTime(with timeZone: TimeZone) -> String {
            Date.shortTimeFormatter.timeZone = timeZone
            return Date.shortTimeFormatter.string(from: self)
        }
    }
    

    date?.shortTime(with: TimeZone(identifier: "GMT")!)   // 10:40 PM +2hs