iOS NSDate()返回不正确的时间 [英] iOS NSDate() returns incorrect time

查看:90
本文介绍了iOS NSDate()返回不正确的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 NSDate()在Swift中获取当前日期。当我创建断点并停止应用程序时,我可以看到设备的系统时间有3个小时的差异。应用程序在真正的iPhone上运行。如何解决这个问题?

I am trying to get current date in Swift using NSDate(). When I create breakpoint and stop application, I can see that there is 3 hours difference with devices' system time. Application is running on real iPhone. How to fix this?

我还在App Delegate中写了以下内容以确定:

I also wrote the following in App Delegate to be sure:

NSTimeZone.setDefaultTimeZone(NSTimeZone(name: "Europe/Kiev")!)

但它仍然不起作用。

推荐答案

它没有返回错误的时间。它返回的时间恰到好处。 NSDate没有任何时区信息。现在,当我们调用NSDate()时,我的计算机和计算机将报告完全相同的时间。

It doesn't return the wrong time. It returns exactly the right time. NSDate doesn't have any timezone information. Right now, my computer and your computer will report the exact same time when we call NSDate ().

NSLog以UTC格式显示NSDate。这就是它所显示的内容。因此,如果我们现在都调用NSLog,您的计算机将记录与我的相同的日期和时间。因为它是相同的日期和时间。

NSLog displays NSDate in UTC. That's just what it displays. So if we both call NSLog right now, your computer will log the same date and time as mine. Because it is the same date and time.

如果要处理NSDate(例如,向用户显示日期和时间),请使用NSCalendar。 NSCalendar在世界各地的NSDate和您希望在用户界面中显示的值之间进行转换,这在伦敦或基辅会有所不同。如果我现在看一下手表,我会看到一个不同于你在手表上看到的时间,这就是NSCalendar的用途。

If you want to process an NSDate (for example, to display the date and time to a user) you use an NSCalendar. The NSCalendar translates between NSDate, which is the same everywhere in the world, to the values that you want to display in your user interface, which will be different in London or in Kiev. If I look on my watch right now, I will see a different time than you see on your watch, and that is what NSCalendar is there for.

这篇关于iOS NSDate()返回不正确的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆