-4

I have a string 20160522115200 and need to convert into yyyy-mm-dd hh:mm:ss format.

Ex: 2016-05-22 11:52:00  yyyy-mm-dd hh:mm:ss
Sohil R. Memon
  • 9,404
  • 1
  • 31
  • 57
Reddy
  • 29
  • 1
  • 5
  • @GrzegorzKrukowski No it's not - what you linked deals with Objective-c not Swift and also deals with converting NSDate to NSString, not the other way around. – Albert Renshaw May 26 '16 at 07:42
  • 2
    OK, so the OP needs to Google `swift Convert String to NSDate` which takes about 3 seconds and returns 19,600 results. – Pekka May 26 '16 at 07:53
  • Converting from Obj-C to Swift (same API) is so extremely hard... oh well... – Eiko May 26 '16 at 08:03

2 Answers2

1

Try below line of code:

 NSString * str = @"20160522115200";
 NSDateFormatter * d1 = [[NSDateFormatter alloc] init];
 d1.dateFormat = @"yyyyMMddhhmmss";
 NSDate * date = [d1 dateFromString: str];
 d1.dateFormat = @"yyyy-MM-dd hh:mm:ss";
 str = [d1 stringFromDate: date];
Payal Maniyar
  • 4,293
  • 3
  • 25
  • 51
0

In Swift You will need to do the following:

Format the current Date String :

let formatter = NSDateFormatter()
formatter.dateFormat = "yyyyMMddhhmmss"
let date = formatter.dateFromString("20160522115200")

Convert the new String to your new format :

let formatterToNewDate = NSDateFormatter()
formatterToNewDate.dateFormat = "yyyy-MM-dd hh:mm:ss"
let myNewDate = formatterToNewDate.stringFromDate(date!)
AaoIi
  • 8,288
  • 6
  • 45
  • 87