I'm loading a string from a byte array in Swift using the following code
let bytes = data[position...position + length]
guard let let dateString = String(bytes: bytes, encoding: .utf8)
else {return}
This gives me a valid string, for example "20160714"
.
Using a DateFormatter
I then try and parse a date from the string with the following
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYYMMdd"
let date = dateFormatter.date(from: dateString)
This should work, but date
is always nil
. When I try the same thing in a playground with a string literal (let dateString = "20160714"
) it works as expected, i'm thinking it's something to do with the encoding.
Any help much appreciated.
EDIT: I've tried both YYYY and yyyy for year, both return nil
It's also worth noting that the byte array comes from loading a file into memory using
guard let data = try? NSData(contentsOfFile: urlString,
options: .alwaysMapped)
else {fatalError("Invalid file")}
As requested by @vadian, printing Data(bytes) as NSData
in the console gives the following output
{length = 8, bytes = 0x3230313630373134}