How to format string in Swift using strftime

1.2k views Asked by At

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

2

There are 2 answers

3
Jeffery Thomas On BEST ANSWER

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.

3
Himanshu gupta On

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/