Converting a NSDate to a String and String to a NSDate
Converting a NSDate to a String and back again is easy with a few lines of code.
NSDate to String
let date = NSDate() // Get Todays Date let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd-MM-yyyy" let stringDate: String = dateFormatter.string(from: date as Date) print(stringDate)
String to NSDate
var dateString = "30-03-2016" var dateFormatter = DateFormatter() // Our date format needs to match our input string format dateFormatter.dateFormat = "dd-MM-yyyy" // The below line is optional, as NSDate uses the GMT +0 timezone by default // The output day may be slightly off due your timezone // This will align it with the NSDate timezone default GMT + 0 // Keep in mind users of your app all have different timezones and this will make the date use GMT+0 timezone instead of a users local one //dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00") as TimeZone! var dateFromString = dateFormatter.date(from: dateString) print(dateString)
Easy peasy – just when converting a String to NSDate remmber the dateFormatter must match the same format as your String! You can find a cheat sheet on the date formatter dateFormat codes here.