NSDate
是一個時間點,你可以稱之爲絕對時間。這一次對地球上的每個地方都是一樣的。 NSDate
並不代表格式化爲特定位置的人物喜好的時間。這種分化非常重要。
單個NSDate()可以在多個時區中有多個表示。
爲了更直觀,這5個時鐘週期都代表一個單一的時間點(NSDate
實例):
他們只是顯示同一時間點的不同表現。
人們可以說這些時鐘是什麼NSDateFormatter.stringFromDate()
是。他們將絕對時間點轉化爲當地表示。
要在不改變時區之間進行轉換NSDate
,請更改NSDateFormatter
的時區。如果您從服務器獲取日期字符串在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)
如果你想發送的日期字符串返回到你的服務器,你需要的NSDate並把它通過你的UTC dateFormatter。
// send back time to server
let dateString = utcDateFormatter.stringFromDate(NSDate())
這個答案比我的要好得多,如果你添加了相應的文檔鏈接,這將是完美的。 – 2015-04-03 09:04:51
如何設置默認時區與在格式化程序中添加時區不同?是否可以使用[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithName:selectedTimeZone]] 這將覆蓋本地時區。我仍然需要處理NSDateFormatter中的任何事情嗎? – Tariq 2015-04-03 11:51:38