Converting an NSDate
object to string is just 3 steps.
NSDateFormatter
objectlet dateFormatter = NSDateFormatter()
let dateFormatter = DateFormatter()
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = "yyyy-MM-dd 'at' HH:mm"
dateFormatter.dateFormat = @"yyyy-MM-dd 'at' HH:mm";
let date = NSDate() // your NSDate object
let dateString = dateFormatter.stringFromDate(date)
let date = Date() // your NSDate object
let dateString = dateFormatter.stringFromDate(date)
NSDate *date = [NSDate date]; // your NSDate object
NSString *dateString = [dateFormatter stringFromDate:date];
This will give output something like this: 2001-01-02 at 13:00
Note
Creating an
NSDateFormatter
instance is an expensive operation, so it is recommended to create it once and reuse when possible.
extension Date {
func toString() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd yyyy"
return dateFormatter.string(from: self)
}
}
Useful links for swift date-formation swiftly-getting-human-readable-date-nsdateformatter.
For constructing date formats see date format patterns.