Terrance Terrance - 6 months ago 45
Swift Question

Dateformatter returning nil

The function below works in a playground but when I run it in my app for some reason the

date
and
fDate
returns
nil
. Is there something I'm missing here?

extension NSDate{
func APIformatDate(dateString: String)->String{
p let dateFormatter = NSDateFormatter()
let date = dateFormatter.dateFromString(dateString)
dateFormatter.dateFormat = "dd-MMM"
let fDate = dateFormatter.stringFromDate(date!)
return fDate
}

}
let a = NSDate().APIformatDate("2025-12-18T01:30:00Z")


Works in Playground = http://swiftlang.ng.bluemix.net/#/repl/db3df0ceebe0bc9061c9b200606b59ce93b43c7889f1aa056f4d7afb160beac9

Answer

For me, it doesn't work in an iOS playground under Xcode 7.3.1. It crashes trying to unwrap date because "2025-12-18T01:30:00Z" doesn't match the default format used by NSDateFormatter, so dateFromString returns nil. Moral: don't trust the IBM Swift Sandbox to behave exactly like iOS or OS X.

Also, since APIformatDate doesn't refer to self, it should be a class or static method, or a method on String, so you don't have to create an NSDate object just to call it.

Also2, it is expensive to create an NSDateFormatter, so if you're going to call this function often, you should create one formatter for each format and keep them around.

extension NSDate {

    static func apiFormatted(iso8601String string: String) -> String {
        return apiFormatter.stringFromDate(iso8601Formatter.dateFromString(string)!)
    }

    private static let iso8601Formatter: NSDateFormatter = {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
        return formatter
    }()

    private static let apiFormatter: NSDateFormatter = {
        let parser = NSDateFormatter()
        parser.dateFormat = "dd-MMM"
        return parser
    }()

}