I'm trying to format this date: 2014-03-18T03:31:14.000Z
Into this one: 2014-03-18 3:31 am
I'd like split it and store it in an array.
I'm trying to format this date: 2014-03-18T03:31:14.000Z
Into this one: 2014-03-18 3:31 am
I'd like split it and store it in an array.
You need to create a NSDate
object and then use a NSDateFormatter
to create a string for the date portion and another for the time portion. Here, I saved you the trouble (make sure the dateFormat
is correct):
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = formatter.dateFromString("2014-03-18T03:31:14.000Z")
formatter.locale = NSLocale.currentLocale()
formatter.dateStyle = .LongStyle
formatter.timeStyle = .NoStyle
let dateString = formatter.stringFromDate(date!)
formatter.dateStyle = .NoStyle
formatter.timeStyle = .LongStyle
let timeString = formatter.stringFromDate(date!)
The following will do. Note that I used stringFromDate
twice with different format strings, instead of splitting the formatted date as you wanted. Using stringFromDate
twice is more independent from the format.
Also creation of NSDateFormatter
is a bit expensive, it's best to reuse it.
let z = "2014-03-18T03:31:14.000Z"
let fmt = NSDateFormatter()
fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = fmt.dateFromString(z)!
fmt.timeZone = NSTimeZone(abbreviation: "Australia/Brisbane")
fmt.dateFormat = "yyyy-MM-dd"
let dateString = fmt.stringFromDate(date)
fmt.dateFormat = "h:mm a"
let timeString = fmt.stringFromDate(date)
print("date: \(dateString), time: \(timeString)")