p0lAris p0lAris - 1 month ago 9
Swift Question

Swift NSDate UTC time and local time

In objective-c, the following code results in the UTC date time information using the

date
API.

NSDate *currentUTCDate = [NSDate date]


In Swift however,

let date = NSDate.date()


results in local date and time.

I have two questions:


  1. How can I get UTC time and local time (well
    date
    gives local time) in
    NSDate
    objects.

  2. How can I get precision for seconds from the
    NSDate
    object.



EDIT 1: Thanks for all the inputs but I am not looking for
NSDateFormatter
objects or string values. I am simply looking for NSDate objects (however we cook them up but that's the requirement).
See point 1.

Answer

The documentation says that the date method returns a new date set to the current date and time regardless of the language used.

The issue probably sits somewhere where you present the date using NSDateFormatter. NSDate is just a point on a time line. There is no time zones when talking about NSDate. I made a test.

Swift

print(NSDate.date())

After latest updates, the new syntax is:

print(NSDate())

Output: 2014-07-23 17:56:45 +0000

Objective-C

NSLog(@"%@", [NSDate date]);

Output: 2014-07-23 17:58:15 +0000

Result - No difference.