将String转换为NSDate时,会减去小时

时间:2015-07-13 17:44:00

标签: ios cocoa-touch nsdate nsdateformatter

这是代码:

let dateString = "2015-07-13T17:32:32.781Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"
var theDate = dateFormatter.dateFromString(dateString)!
println(theDate)  // 2015-07-13 16:32:32 +0000

在此过程中,将一小时减去原始日期。为什么呢?

1 个答案:

答案 0 :(得分:1)

@mipadi已经很好地解释了这个问题,所以我认为你应该把时区设置为UTC。

    let dateString = "2015-07-13T17:32:32.781Z"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
    var theDate = dateFormatter.dateFromString(dateString)!
    println(theDate)