Swift: NSDate formatting with strftime & localtime

ma11hew28 picture ma11hew28 · Jun 17, 2014 · Viewed 16.6k times · Source

How do I convert the following Objective-C code into Swift code?

#define MAX_SIZE 11
char buffer[MAX_SIZE];
time_t time = [[NSDate date] timeIntervalSince1970];
strftime(buffer, MAX_SIZE, "%-l:%M\u2008%p", localtime(&time));
NSString *dateString = [NSString stringWithUTF8String:buffer];
NSLog(@"dateString: %@", dateString); // dateString: 11:56 PM

I'm formatting a date.

Answer

Grimxn picture Grimxn · Jun 17, 2014

As the commentators @BryanChen and @JasonCoco said, use NSDateFormatter.

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd 'at' h:mm a" // superset of OP's format
let str = dateFormatter.stringFromDate(NSDate())

A full description of the format strings is available in "Data Formatting Guide".