Swift: Convert Normal String to YYYY-MM-DD type String?

5 Solutions Collect From Internet About “Swift: Convert Normal String to YYYY-MM-DD type String?”

For only converting string to given format
you can use insert sunction of swift

var a = "20160114"

a.insert("-", atIndex: a.startIndex.advancedBy(4))
a.insert("-", atIndex: a.startIndex.advancedBy(4+1+2))

print(a)

print : “2016-01-14”

    let dateString = "20160114"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyyMMdd"

    let dateObj = dateFormatter.dateFromString(dateString)

    dateFormatter.dateFormat = "yyyy-MM-dd"
    print("Dateobj: \(dateFormatter.stringFromDate(dateObj!))")
let dateformattor = NSDateFormatter()
dateformattor.dateFormat = "yyyyMMdd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
//  here just pass your string that you want to convert into date.
let dt = "20160114" 
let dt1 = dateformattor.dateFromString(dt as String)
dateformattor.dateFormat = "yyyy-MM-dd"
dateformattor.timeZone = NSTimeZone.localTimeZone()
print("Time :",dateformattor.stringFromDate(dt1!))

Output :

Time : 2016-01-14

this might not be applicable in general when dealing with dates and times, but if you only need to insert dashes (format is guaranteed to be same), this is much simpler solution

var str = "20160112"
str.characters.insert("-", at: str.index(str.startIndex, offsetBy: 6))
str.characters.insert("-", at: str.index(str.startIndex, offsetBy: 4))
print(str) // outputs "2016-01-12"
    var str = "20160518"
    let strCpoy = str
    str.insert("-", at: strCpoy.index(strCpoy.startIndex, offsetBy: 4))
    str.insert("-", at: strCpoy.index(strCpoy.startIndex, offsetBy: 7))
    print(str)