Search code examples
swiftdatensdateformatter

Date format ( "yyyy-MM-dd HH:mm:ss VV") returns nil


I'm trying to change format my date for in-app purchases but returns nil in real devices but in simulator it working great.

let DateString = "2016-01-21 00:29:09 Etc/GMT"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
var dateObject = dateFormatter.date(from: DateString)
print(dateObject)

Solution

  • You should always set the locale of your DateFormatter when dealing with hardcoded Date formats. You can use en_US_POSIX in most scenarios.

    let dateString = "2016-01-21 00:29:09 Etc/GMT"
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"
    let dateObject = dateFormatter.date(from: dateString)
    print(dateObject)