NSDate 比用户本地时间晚一小时

NSDate is one hour behind user's local time

我目前根据 US/Eastern 时区在 Parse 中存储日期。但是,当我从 Parse 获取对象并设置它们的日期属性时,时间总是显示为比预期时间早一小时。

我相信这是夏令时的结果,但我不确定如何在不硬编码增加一个额外小时的情况下解决这个问题。

var objectDate = object.createdAt! // object is from Parse query
let calendar = NSCalendar.currentCalendar() // I am in Pacific timezone
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "E, M/d, h:mm a"
dateFormatter.timeZone = NSTimeZone(name: "US/Eastern") // date is 8 am Eastern time
var formattedDate = dateFormatter.stringFromDate(objectDate)
// formattedDate prints as 4 am, but should be 5 am

将日期视为其中没有时区会有所帮助。我的意思是,当你说 "Save the time and day right now" 时,NSDate 对象应该使用 UTC 时间,因为它真的 没关系 。当你去查看日期时,你从某个时区或格式的角度查看它:

所以,它可能是这样的:

//this saves the date as NOW, whenever it is called
var date = NSDate()
//it doesn't matter what timezone you want it to save in, because it always
//saves in a way that it KNOWS when it occurred

//when I want to view the value of the date from a "PST" timezone perspective
//I need to use an NSDateFormatter to set my point of view for the date
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(name: "PST") //sets formatter to show what PST zone is
formatter.dateFormat = "hh:mm a z" //formats the time to show as 07:30 PST

//now that we have the date formatted, we could do something like set a label to it
@IBOutlet var dateLabel: UILabel!
dateLabel.text = formatter.stringFromDate(date)

所以,正如您在上面看到的,日期并没有真正保存为任何特定时区。它只是以代码可以计算出确切 time/date 的方式保存。然后,当您引用它并使用 NSDateFormatter 时,您可以根据需要查看日期。

感谢@Charlie 的帮助。为了解决我的一小时时差问题,我添加了一个 if 语句来检查用户当前是否处于夏令时。如果用户是,那么我们将当前时间加一小时:

if (NSTimeZone.systemTimeZone().daylightSavingTime == true) {
    var newDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitHour, value: +1, toDate: currentDate, options: NSCalendarOptions(0))!
}