Reputation: 99
I am trying to reformat the time that I am reading off from a String from a JSON API. It is reading from the JSON fine because it gives me the result- the String "2020-05-12T00:00:00:00.000 How can I convert this string it is giving in to an NSDate because I have looked at previous questions and the solution they are giving me is giving me the error that leads to the string having a value of nil
Upvotes: 0
Views: 44
Reputation: 1108
Try using following as format - "yyyy-MM-dd'T'HH:mm:ss:SS.SSS"
let dateString = "2020-05-12T00:00:00:00.000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SS.SSS"
let date = dateFormatter.date(from: dateString)!
print(date)
// Prints Date object
// 2020-05-12 00:00:00 +0000
The last 00.000 tells us fractional of a second, which is represented by SS.SSS Refer to this page for more date formatter related queries.
Two things to note about the fractional second. First, it does not round, it just shows the appropriate places (otherwise the 2 digit fractional second would show 7 ms as “01”). Secondly, the Unicode standard lets you use as many as you want, so “SSSSS” is valid. However, DateFormatter will not show anything below milliseconds, it will just show 0s below that. So 123456789 nanoseconds with a “SSSSSSSSS” format string will show up as “123000000”
Upvotes: 2