Reputation: 6238
EDIT: Please read carefully I need to support this specific format, I cannot just go and use a hardcoded format using NSDateFormatter
Hi I've got the task to format all dates in our app using settings retrieved from OUR API, the format in this case is supported by strftime functions.
How should I go and use these in swift.
example format for date and time: "date_format": "%d %B %Y" "time_format": "%H:%M"
I found the strtime function but I'm not sure how I should use it or even if I should. I've also only found examples in Objective-C
Upvotes: 5
Views: 1319
Reputation: 42588
I hope you can find a better way to satisfy this requirement, but here's the code.
let bufferSize = 255
var buffer = [Int8](count: bufferSize, repeatedValue: 0)
var timeValue = time(nil)
let tmValue = localtime(&timeValue)
strftime(&buffer, UInt(bufferSize), "%d %B %Y", tmValue)
let dateFormat = String(CString: buffer, encoding: NSUTF8StringEncoding)!
strftime(&buffer, UInt(bufferSize), "%H:%M", tmValue)
let timeFormat = String(CString: buffer, encoding: NSUTF8StringEncoding)!
NOTE: I updated the code just a bit for clarity.
Upvotes: 4
Reputation: 650
you can use something like this:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd 'at' h:mm a"
let str = dateFormatter.stringFromDate(NSDate())
and for detail info - https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/
Upvotes: 1