如何将服务器响应date转换为本地时区?
在API调用响应中,我得到不同时区的date。 我想将其转换为用户的本地时区,用户可以从ios时区列表中select任何时区。 这都是本地的。 我们永远不会发送选定的用户时区到服务器。
同时使任何API调用可以说我正在select器中创build一个事件与选定的开始date。 我应该发送全球时区不与用户select的时区,因为它是本地的应用程序。
目前我正在改变select的defaultTimeZone,以便我得到适当的当前date等。并使用setTimeZone NSDateFormatter … [NSTimeZone timeZoneWithName …
这是一个更好的方法来改变应用程序的所有本地的defaultTimeZone? 在将NSdate发送到服务器时,我应该如何将NSdate转换回全局date?
NSDate
是一个时间点,你可以称之为绝对时间。 这一次对于地球上的每个地方都是一样的。 NSDate
不代表格式化为特定位置的人的喜好的时间。 这种分化是非常重要的。
单个NSDate()可以在多个时区中有多个表示。
为了使它更直观,这5个时钟都代表一个时间点( NSDate
实例):
他们只是performance出同一时间点的不同表示。
人们可以说这些时钟是NSDateFormatter.stringFromDate()
是什么。 他们将绝对时间点转换为当地表示。
要在不同的时区之间进行转换,您不要更改NSDate
,您可以更改NSDateFormatter
的时区。 如果从服务器获得的datestring是UTC,则需要一个使用UTC作为时区的NSDateFormatter:
let utcDateFormatter = NSDateFormatter() utcDateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0) utcDateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") utcDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let serverString = "2015-04-03 12:34:56" // date from server, as date representation in UTC let date = utcDateFormatter.dateFromString(serverString) // date you got from server, as point in time
要显示服务器的时间给你的用户,你把该NSDate并把它放到另一个dateFormatter:
// display absolute time from server as timezone aware string let localDateFormatter = NSDateFormatter() localDateFormatter.dateStyle = NSDateFormatterStyle.LongStyle localDateFormatter.timeStyle = NSDateFormatterStyle.LongStyle let localDateString = localDateFormatter.stringFromDate(date)
如果你想发送一个datestring到你的服务器,你需要一个NSDate并通过你的UTC dateFormatter。
// send back time to server let dateString = utcDateFormatter.stringFromDate(NSDate())