LEVIS OGCPAS LEVIS OGCPAS - 18 days ago 5
iOS Question

swift - Converting String to NSDate

I'm trying to convert a Date and Time String to NSDate with Swift, But the problem is The time is not converting perfectly, Even i set my Timezone correctly, Here's my code:

var dateStr = "2015-10-16 08:00 AM"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 28800)
var date = dateFormatter.dateFromString(dateStr)
print(date!)


And it prints out like this:
2015-10-16 00:00:00 +0000
What do you think seems to be the problem? Thanks!

Answer

Nothing wrong here. You should convert date to String before print it.

    let dateStr = "2015-10-16 08:00 AM"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
    dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 28800)
    let date = dateFormatter.dateFromString(dateStr)
    print(dateFormatter.stringFromDate(date!))

or as in Swift 3

    let dateStr = "2015-10-16 08:00 AM"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 28800)
    let date = dateFormatter.date(from: dateString)
    print(dateFormatter.string(from: date))

The same result: 2015-10-16 08:00 AM