1

I am trying to convert my string to a date using a static date formatter. When I make the call to stringToDate() using the variables below, a nil value is returned.

I've checked previous posts about this issue where people are saying it's because of the dateformatter locale or timeZone. However, that doesn't seem to be the issue in this case.

Does anyone know what the issue could be in this case? My code is below:

import Foundation

class DateHelper {

    private static let dateFormatter: DateFormatter = {
        let df = DateFormatter()
        df.dateFormat = "yyyy-MM-dd hh:mm:ss"
        df.locale = Locale(identifier: "en_GB")
        df.timeZone = TimeZone.current
        return df
    }()

    static func stringToDate(str: String, with dateFormat: String) -> Date? {
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.date(from: str)

        return date
    }
}

var myDate = Date()
var dateStr = "2019-02-19T17:10:08+0000"

print(DateHelper.stringToDate(str: dateStr, with: "MMM d yyyy")) // prints nil
Simon Jackson
  • 181
  • 1
  • 1
  • 7
  • Don't change the `dateFormat` of the shared `dateFormatter` instance. You're just asking for trouble. – Alexander Feb 19 '19 at 17:54
  • 1
    Not to mention that none of the date formats in your code match the string `"2019-02-19T17:10:08+0000"`. – rmaddy Feb 19 '19 at 17:58
  • 1
    Possible duplicate of [Dateformatter returns nil date](https://stackoverflow.com/questions/51325788/dateformatter-returns-nil-date) – jscs Feb 19 '19 at 18:38
  • 2019-02-19T17:10:08+0000 and yyyy-MM-dd hh:mm:ss format not match. please search solution. There are lots of solution available. – Hardik Thakkar Feb 21 '19 at 13:23

2 Answers2

1

Looks like your string is in ISO8601 format. Use the ISO8601DateFormatter to get date instance. You can use ISO8601DateFormatter.Options to parse varieties of ISO8601 formats. For your string,

For Swift 4.2.1

let formatter = ISO8601DateFormatter()
let date = formatter.date(from: dateStr)
print(date!)

Should output

"2019-02-19 17:10:08 +0000\n"

Sandeep Joshi
  • 316
  • 3
  • 6
0

Your date format doesn't match your input date. Try this code:

print(DateHelper.stringToDate(str: dateStr, with: "yyyy-MM-dd'T'HH:mm:ssZZZZZ"))

Hope this helps.

qtngo
  • 1,594
  • 1
  • 11
  • 13