Search code examples
iosswiftnsdateformatter

Time Format Contains Colon(:) Not supported by iOS 12.2


I'm using iPhone SE which contains iOS 12.2. I'm converting my date to following time format (h:MM a) which convert correct time but colon(:) between hour and minute removed.

My code as follows to convert time:

static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? {
    let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
    let dateFormatter = DateFormatter()
    dateFormatter.locale = NSLocale.current
    dateFormatter.dateFormat = format //Specify your format that you want
    return dateFormatter.string(from: date)
}

I'm using this method to convert time, where timestamp contain UNIX time value like 1555395758

I'm using above function as following:

guard let time = Date.getDateInWithoutTimeZone(format: "h:MM a", from: 1555395758) else {
    return
}

And getting following output:

1104 AM

Am I doing anything wrong ? Or Is it issue with iOS 12.2?


Solution

  • Just change date format h:MM a to hh:mm a

    Please refer below code.

    static func getDateInWithoutTimeZone(format: String, from timeStamp: Int64) -> String? {
        let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = format //Specify your format that you want
        return dateFormatter.string(from: date)
    }
    
    guard let time = getDateInWithoutTimeZone(format: "hh:mm a", from: 1555395758) else {
        return
    }
    print(time)
    

    Console Log

    MM which stands for months, not minutes.