NSDate 在 swift 中设置时区

NSDate set timezone in swift

我如何 return 来自字符串的预定义时区中的 NSDate

let responseString = "2015-8-17 GMT+05:30"
var dFormatter = NSDateFormatter()
dFormatter.dateFormat = "yyyy-M-dd ZZZZ"
var serverTime = dFormatter.dateFromString(responseString)
println("NSDate : \(serverTime!)")

以上代码return时间为

2015-08-16 18:30:00 +0000

必须将日期格式分配给日期格式化程序的 dateFormat 属性。

let date = NSDate.date()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let str = dateFormatter.stringFromDate(date)
println(str)

这将使用设备上的默认时区打印日期。只有当你想要根据不同的时区输出时,你才会添加例如

Swift3.*

dateFormatter.timeZone = NSTimeZone(name: "UTC")

Swift 4.*

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

另请参考linkhttp://www.brianjcoleman.com/tutorial-nsdate-in-swift/

how can i return a NSDate in a predefined time zone?

你不能。

NSDate 的实例不包含任何有关时区或日历的信息。它只是简单地标识了世界时的一点。

您可以在任何您想要的日历中解释这个 NSDate 对象。 Swift 的字符串插值(示例代码的最后一行)使用了使用 UTC 的 NSDateFormatter(即输出中的“+0000”)。

如果您希望 NSDate 的值作为当前用户日历中的字符串,您必须为此明确设置日期格式化程序。

Swift 4.0

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

无论语言如何,数字 1 都表示 1。然而在英语中它拼写为 one,在西班牙语中它是 una,在阿拉伯语中它是 wahid,等等

同样,1970 年过去了 123982373 秒,在不同的时区或日历格式中会有不同的反映,但 1970 年过去了 123982373 秒


3秒和7秒相差4秒。那不需要日历。你也不需要 calendar/timezone 来知道这两个 Epoch times 1585420200 和 1584729000

之间的时间差

日期只是从 1970 年 1 月 1 日(午夜 UTC/GMT)开始的 timeInterval。日期也恰好有一个字符串表示。

重复 Nikolia 的回答,Swift 的默认字符串插值 (2015-08-16 18:30:00 +0000) 使用使用 UTC 的 DateFormatter(即输出中的“+0000”)。

使用时区的日历为我们提供了一种上下文表示,这比试图计算两个巨大数字之间的差异更容易理解。

表示单个日期(想想自 1970 年以来的单个 timeInterval)每个日历都有不同的字符串解释。最重要的是,日历本身会因时区而异

我强烈建议您去尝试一下这个 Epoch converter site,看看选择不同的时区将如何导致相同 moment/date/timeInterval 的字符串表示发生变化


我也推荐看。主要是这部分:

Timezone is just an amendment to the timestamp string, it's not considered by the date formatter.

To consider the time zone you have to set the timeZone of the formatter

dateFormatter.timeZone = TimeZone(secondsFromGMT: -14400)

如果输入字符串始终具有相同的时区,则可以创建两个日期格式化程序来输出本地时区(或指定的时区):

let timeFormatterGet = DateFormatter()
timeFormatterGet.dateFormat = "h:mm a"
timeFormatterGet.timeZone = TimeZone(abbreviation: "PST")

let timeFormatterPrint = DateFormatter()
timeFormatterPrint.dateFormat = "h:mm a"
// timeFormatterPrint.timeZone = TimeZone(abbreviation: "EST") // if you want to specify timezone for output, otherwise leave this line blank and it will default to devices timezone

if let date = timeFormatterGet.date(from: "3:30 PM") {
    print(timeFormatterPrint.string(from: date)). // "6:30 PM" if device in EST
} else {
   print("There was an error decoding the string")
}