swift - 将字符串转换为NSDate

时间:2015-10-15 09:35:26

标签: ios swift nsdate nsdateformatter

我试图用Swift将日期和时间字符串转换为NSDate,但问题是时间不能完美转换,即使我正确设置了我的时区,这是我的代码:

    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!)

它打印出来像这样:2015-10-16 00:00:00 +0000您认为这似乎是什么问题?谢谢!

1 个答案:

答案 0 :(得分:4)

这里没有错。在打印之前,您应该将date转换为String

    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!))

或在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))

同样的结果:2015-10-16 08:00 AM