Search code examples
iosswiftstrftime

How to format string in Swift using strftime


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


Solution

  • 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.