2014-07-05 19 views
1

我在操场下面的代码:为什么Swift Playground中的结果与在应用程序中执行的结果不同?

import Cocoa 

let date = NSDate() 
let calendar = NSCalendar(calendarIdentifier:NSGregorianCalendar) 
let components = calendar.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit, fromDate: date) 

let dateStrippedOfTimeComponent:NSDate = calendar.dateFromComponents(components) 

在操场的结果是2014年7月5日00:00这是我想

但是相同的代码,在我的viewController作为的一部分时func给出了结果2014年7月4日23:00,而且当前的NSDate()结果比我的我的Mac显示提前了一个小时。有人能告诉我如何解决这个问题吗?非常感谢,谢谢。

+0

你在哪里运行的代码没有给出想要的结果?在iOS设备上?时间(和时区)设置是否正确? – Undo

+0

在Xcode 6.0中运行它,错误的结果出现在调试器中... – agf119105

+0

是的,你是在Mac上还是在iOS设备上运行它?或者在iOS模拟器上? – Undo

回答

1

这仅仅是一个显示问题。 这两个日期对象是完全一样,但操场和应用程序在打印结果时使用了两个不同的时区。

NSDate是时间瞬间的纯粹表示。

无论何时您需要显示它,您可以决定格式,区域设置,时区和其他可视化相关信息。作为一个例子,你可以在操场上运行它:

let date = NSDate() 
// "Jul 6, 2014, 11:43 AM" in my system timezone (Italy) 

let calendar = NSCalendar(calendarIdentifier:NSGregorianCalendar) 
let components = calendar.components(NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit, fromDate: date) 
let dateStrippedOfTimeComponent = calendar.dateFromComponents(components) 

let dateFormatter = NSDateFormatter() 
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle 
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle 

dateFormatter.timeZone = NSTimeZone(abbreviation: "EST") 
let estDate = dateFormatter.stringFromDate(dateStrippedOfTimeComponent) 
// "Jul 5, 2014, 6:00:00 PM" in NYC 

dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") 
let utcDate = dateFormatter.stringFromDate(dateStrippedOfTimeComponent) 
// "Jul 5, 2014, 10:00:00 PM" in London 
+0

当我看着时区。该应用正在修正英国夏令时。我只是认为如果应用的用户在美国,这是一个真正的问题 - 您不能强制应用程序认为它在伦敦,因为应用程序的其他功能与人员默认时区相关联。我通过使用.secondsFromGMT来找到一个中间解决方案,因为这应该可以在英国夏令时更正 – agf119105

+0

它取决于日期格式化程序中设置的时区,这是系统默认设置的时区之一。如果您希望日期与用户的时区匹配,则无需执行其他任何操作,否则可以手动指定时区 –

相关问题