NSDate比用户当地时间晚一个小时

时间:2015-09-03 23:50:51

标签: ios swift parse-platform nsdate nstimezone

我目前根据美国/东部时区将日期存储在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

2 个答案:

答案 0 :(得分:1)

将日期视为没有时区作为其中的一部分是有帮助的。我的意思是,当你说'#34;现在节省时间和时间" 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)

因此,如您所见,日期并未真正保存为任何特定时区。它只是以代码可以确定准确时间/日期的方式保存。然后,当您引用它并使用NSDateFormatter时,您可以查看所需的日期。

答案 1 :(得分:1)

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

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