swift how to convert string to date fraction seconds

I have a string want to convert to date, but below code,

that str

print out show

Optional(2016-04-25 17:00:16 +0000)


I want to know how to show exact what it is like

Optional(2016-04-26T03:00:16.047)


var str = "2016-04-26T03:00:16.047"

let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"

dateFormatter.timeZone = NSTimeZone(name: "UTC")

let date = dateFormatter.dateFromString(str)

print(date) //Optional(2016-04-25 17:00:16 +0000)

Is the problem the optional ?


if you print(date!), the optional will clear

IMPORTANT If you’re using NSDateFormatter with fixed-format strings, you need to lock down the locale. QA1480 NSDateFormatter and Internet Dates explains why that’s important.

As to why you’re not seeing fractional seconds, that’s a limitation of NSDate’s

description
property. If you add this line to your code:
print(date?.timeIntervalSinceReferenceDate)

you’ll see this:

Optional(483332416.04699993)

indicating that the fractional part is present and correct (modulo floating point rounding fun).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
swift how to convert string to date fraction seconds
 
 
Q