NSDate在swift中设置了时区

时间:2015-08-17 09:09:20

标签: swift nsdate

如何从字符串

返回预定义时区的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!)")

上面的代码将时间返回为

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

5 个答案:

答案 0 :(得分:35)

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

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

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

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

也请参阅链接http://www.brianjcoleman.com/tutorial-nsdate-in-swift/

答案 1 :(得分:10)

  

如何在预定义的时区内返回NSDate?

你不能。

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

您可以在任何日历中解释此NSDate对象。 Swift的字符串插值(示例代码的最后一行)使用了NSDateFormatter,它使用UTC(" + 0000"在输出中)。

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

答案 2 :(得分:5)

Swift 4.0

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

答案 3 :(得分:0)

数字1表示1,与语言无关。然而,英语拼写为1,西班牙语拼写为una,阿拉伯语拼写为wahid,等等。

类似地,通过1970年的123982373秒将在不同的时区或日历格式中进行不同的反映,但是仍然是通过1970年的123982373秒。


3秒和7秒之间的差是4秒。那不需要日历。您也不需要日历/时区来了解这两个Epoch times 1585420200和1584729000

之间的时差

日期只是1970年1月1日(UTC / GMT午夜)以来的 timeInterval 。日期也恰好具有字符串表示形式。

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

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

意味着单个日期(从1970年开始,就想到单个timeInterval)每个日历将具有不同的字符串解释。最重要的是,日历本身会根据时区而变化

我强烈建议您尝试使用此Epoch converter site,看看选择不同的时区将如何导致相同的矩/日期/时间间隔的字符串表示形式发生变化


我还建议您查看this answer。主要是这部分:

时区只是对时间戳字符串的修正,日期格式化程序未考虑它。

要考虑时区,您必须设置格式器的timeZone

dateFormatter.timeZone = TimeZone(secondsFromGMT: -14400)

答案 4 :(得分:0)

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

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")
}