Search code examples
ioscocoa-touchnsattributedstringtime-format

Time display as in system clock


I want to make the display of time as in the iOS system clock (time in capital letters, and part of the day small but capital).

iOS Alarm.app table cell

I know that I need the help of an attributed string, but I don’t know how to make it compatible with different time display formats (12 and 24 hours), different languages and a local place.


Solution

  • To get time in string representation according user locale, you can use:

    let formatter = DateFormatter()
    formatter.timeStyle = DateFormatter.Style.short //Or in short formatter.timeStyle = .short
    let time = formatter.string(from: Date())
    

    For example it returns you 23:47 for Russia, and 11:47 PM for US.

    Then we can check if time format returned with day part for user locale. If so we set another font for last two characters in string, which is our day part.

    if let range = time.range(of: formatter.amSymbol) ?? time.range(of: formatter.pmSymbol) {
        let fontSize: CGFloat = 8.0
        let nsRange = NSRange(range, in: time)
    
        let attrString = NSMutableAttributedString(string: time)
        attrString.addAttributes([.font: UIFont.systemFont(ofSize: fontSize)], range: nsRange)
    
        label.attributedText = attrString
    } else {
        label.text = time
    }