我正在尝试使用Swift获取当前日期NSDate().当我创建断点并停止应用程序时,我可以看到设备的系统时间有3个小时的差异.应用程序在真正的iPhone上运行.如何解决这个问题?
我还在App Delegate中写了以下内容以确定:
NSTimeZone.setDefaultTimeZone(NSTimeZone(name: "Europe/Kiev")!)
Run Code Online (Sandbox Code Playgroud)
但它仍然无效.
gna*_*729 11
它没有返回错误的时间.它返回的时间恰到好处.NSDate没有任何时区信息.现在,当我们调用NSDate()时,我的计算机和计算机将报告完全相同的时间.
NSLog以UTC格式显示NSDate.这就是它所显示的内容.因此,如果我们现在都调用NSLog,您的计算机将记录与我的相同的日期和时间.因为它是相同的日期和时间.
如果要处理NSDate(例如,向用户显示日期和时间),请使用NSCalendar.NSCalendar在世界各地的NSDate与您希望在用户界面中显示的值之间进行转换,这在伦敦或基辅会有所不同.如果我现在看一下手表,我会看到与你在手表上看到的不同的时间,这就是NSCalendar的用途.
这是swift 3.0的转换:
func getCurrentLocalDate()-> Date {
var now = Date()
var nowComponents = DateComponents()
let calendar = Calendar.current
nowComponents.year = Calendar.current.component(.year, from: now)
nowComponents.month = Calendar.current.component(.month, from: now)
nowComponents.day = Calendar.current.component(.day, from: now)
nowComponents.hour = Calendar.current.component(.hour, from: now)
nowComponents.minute = Calendar.current.component(.minute, from: now)
nowComponents.second = Calendar.current.component(.second, from: now)
nowComponents.timeZone = TimeZone(abbreviation: "GMT")!
now = calendar.date(from: nowComponents)!
return now as Date
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5215 次 |
| 最近记录: |