我看到NSTimeZone有这些方法:
defaultTimeZone
localTimeZone
systemTimeZone
Run Code Online (Sandbox Code Playgroud)
有人可以用简单的方式向我解释,这些调用之间的差异是什么,何时应该使用而不是另一个?我不明白Apple文档中有关于此的任何内容.
我的国家位于GMT + 0.我们现在是+1小时,因为我们正在夏令时.
当我做
[NSDate date];
Run Code Online (Sandbox Code Playgroud)
它应该返回当前的日期和时间,但是当我这样做时,我收到GMT时间而不考虑夏令时.
这就是文档对date命令的说法
创建并返回设置为当前日期和时间的新日期.
为什么Apple会对我们这样做?为什么一切都如此复杂?这是一个错误吗?有没有办法获得设备当前的实时时间?同一时间显示在设备的时钟上?
我的应用程序取决于日期和时间,并且对于位于夏季或冬季的世界不同时区的用户来说,错误的日期将是一场灾难.
谢谢.
编辑
经过几个答案后,我尝试了这段代码:
NSDate *wrongToday = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *currentTime = [dateFormatter wrongToday];
NSDate *today = [dateFormatter dateFromString:currentTime];
Run Code Online (Sandbox Code Playgroud)
猜怎么着,今天=错误今天...换句话说,没有变化,我继续错误的日期没有夏令时.更令人惊奇的是,currentTime在NSString中显示了夏令时的日期......
任何线索?再次感谢.
let timeZone = NSTimeZone.system.description
let localTimeZone = TimeZone.ReferenceType.local.description
let currentTimeZone = TimeZone.current.description
let defaultTimeZone = TimeZone.ReferenceType.default.description
let autoUpdateTimezon = TimeZone.autoupdatingCurrent.description
print ("System Timezone \(timeZone)")
print ("Local Timezone \(localTimeZone)")
print ("Current Timezone \(currentTimeZone)")
print ("Default Timezone \(defaultTimeZone)")
print ("Auto updating Timezone \(autoUpdateTimezon)")
Run Code Online (Sandbox Code Playgroud)
输出
亚洲系统时区/加尔各答(当前)
本地时区亚洲/加尔各答(自动更新当前)
当前时区亚洲/加尔各答(当前)
默认时区亚洲/加尔各答(当前)
自动更新时区亚洲/加尔各答 (autoupdatingCurrent)
所以,我得到所有的输出都是一样的,所以这些时区之间有什么区别,在这种情况下我们应该使用哪个时区。
问题
我使用以下代码进行日期转换
static func stringToString(strDate:String, fromFormat:String, toFormat:String)->String{
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC") ?? TimeZone(identifier: "UTC") ?? TimeZone.ReferenceType.default
dateFormatter.dateFormat = fromFormat
let currentDate = dateFormatter.date(from: strDate) ?? Date()
dateFormatter.dateFormat …Run Code Online (Sandbox Code Playgroud)