I need to get current time in NSDate, not swift. I tried to do this like on screenshot, but the final nsdate is in wrong timezone.

- 177
- 11
-
2An image of code for debugging is almost as useful as an image of food when you're hungry... *Include your code*, not an image of your code. You can use the [edit] button to fix your question. – Eric Aya May 08 '16 at 15:19
-
Search for "NSDate IS AN ABSOLUTE POINT IN TIME AND HAS NO TIMEZONE" ... – Martin R May 08 '16 at 15:25
1 Answers
An NSDate
does not have a time zone. It records an instant in time on planet Earth. It is DISPLAYED in a particular time zone.
An NSDateFormatter
will convert between NSDate objects and date strings (in either direction).
If you install a time zone into your date formatter then it will convert dates to/from strings using that time zone. If you don't specify a time zone it will use the user's current time zone.
If you try to display an NSDate using the Swift print
statement or NSLog
then it will be displayed in UTC. Always.
The code you've posted that prints strDate, your date string you created using a date formatter, is correct. The line `print(localDate!) is meaningless.
To repeat: NSDate
objects do not have a time zone. When you log them to the console, they will always be displayed in UTC. If you want to see them in your local time zone then you need to use date formatter like you are doing.

- 128,072
- 22
- 173
- 272