Reputation: 1822
I need to convert String simular to "2016-07-10T21:32:20G" to Date. But for some reason I've got only nil again and again.
I've read an article about date formater. And unfortunately haven't fount an answer there. I found something in the documentation. And documentation tels to read about Unicode Date Format Patterns. And it looks similar to mine.
Probably I missed something =(
My Code example. Unfortunately always get nil.
let lastUpdatedDateString = "2016-07-10 21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd hh:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
But this code works fine:
let lastUpdatedDateString = "2016-07-10"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-mm-dd"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
I'm testing it in the playground.
In fact I must convert this String("2016-07-10T21:32:20G") to Date.
PS
Anyway, thanks for attention =)
Upvotes: 0
Views: 88
Reputation: 1521
This is what I get with the playground
let lastUpdatedDateString = "2016-07-10T21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-ddEEEEEHH:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
print(lastUpdated)
and it prints: Optional(2016-07-10 19:32:20 +0000)
(I'm GMT+2)
I don't know what the G stands for so I'm not sure how I can get the last character for the pattern. EEEEE
stands for day of the week (1 character)
EDIT: It seems G
stand for gregorian calendar
so you can parse the last letter out of the string and add this if it's gregorian calendar (but I suppose this is the default value):
dateFormatter.calendar = Calendar(identifier: .gregorian)
If the letter's a J
it's Julian calendar then and you can see this answer to see how to convert gregorian to julian: https://stackoverflow.com/a/12137019/2106940
Upvotes: 1
Reputation: 1549
Think it's just the capitalisation in your formatter. Try this ...
let lastUpdatedDateString = "2016-07-10 21:32:20"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let lastUpdated = dateFormatter.date(from:lastUpdatedDateString)
Upvotes: 2