1

I know these questions are asked all the time about date formatters, however the issue I have is really odd

I need to convert a simple string to date as follows

    let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let dateOfBirthString = "10/20/2002"
let dob: Date? = dateFormatter.date(from: dateOfBirthString)

This works fine in a playground but always returns nil in the app (with those exact values (albeit properties rather than hard coded strings)

Any help would be appreciated, its driving me nuts

user499846
  • 681
  • 3
  • 11
  • 24
  • In the real app, are you 100% positive that the string really is `"10/20/2002"` with no whitespace or any other characters in the string? – rmaddy Oct 20 '19 at 22:54
  • I printed the string out to copy into the playground – user499846 Oct 20 '19 at 23:02
  • That doesn't confirm whether the real string has any whitespace of any kind or not. Print the length of the string and make sure it is 10. – rmaddy Oct 20 '19 at 23:03
  • (lldb) po dateOfBirthString ▿ Optional - some : "10/20/2002" (lldb) po dateOfBirthString.count 10 – user499846 Oct 20 '19 at 23:04
  • Does seem to be something strange going on. Just tried your code, and when I examine dob it comes up as nil, but when I examine it's description, I get the string represenation of the date:(lldb) e dob (Date?) $R0 = nil (lldb) e dob?.description (String?) $R2 = "2002-10-19 23:00:00 +0000" (lldb) – flanker Oct 20 '19 at 23:29
  • make sure to set your date formatter locale to `"en_US_POSIX"`. you should also set your date formatter's calendar https://stackoverflow.com/q/32408898/2303865 – Leo Dabus Oct 20 '19 at 23:59

1 Answers1

0
extension String {

func toDateTime() -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    dateFormatter.timeZone = TimeZone(identifier: "UTC")
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    guard let date = dateFormatter.date(from: self) else {
        preconditionFailure("Take a look to your format")
    }
    return date
}
}

try this extension

let dateOfBirthString = "10/20/2002"
let dob: Date? = dateOfBirthString.toDateTime()

use this extension like this and if you get any error then feel free to comment below

Habin Lama
  • 529
  • 5
  • 19
  • Hey thanks this solved it - just for reference your second example creates a date formatter and string that's not needed. Also for the string extension I passed a parameter for the format type so I can utilise it for different date formats - thanks this was driving me nuts! – user499846 Oct 21 '19 at 10:36
  • Okey I get it and happy to help you. – Habin Lama Oct 21 '19 at 11:02
  • Thanks - really appreciate the help – user499846 Oct 21 '19 at 11:04