Taras Nikulin Taras Nikulin - 2 years ago 319
Swift Question

How to get current NSDate in current timezone?

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.enter image description here

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download