13

I would like to get UTC timestamp. I cant do it like this [[NSDate date] timeIntervalSince1970]; becouse it returns timestamp in local timezone. How can I get timestamp in UTC in iOS?

Edit

Solved I can use [[NSDate date] timeIntervalSince1970]; :)

Community
  • 1
  • 1
AYMADA
  • 889
  • 3
  • 17
  • 37

3 Answers3

13

See answer by Pawel here: Get current date in milliseconds

He refers to using CFAbsoluteTimeGetCurrent();

which is documented here.

Since it is the system time, just correct for time interval offset to GMT.

Nevertheless using your code works as well if you correct for the local timezone.

You get the timezone offset by calling

[[NSTimeZone systemTimeZone] secondsFromGMT];

or

[[NSTimeZone systemTimeZone] secondsFromGMTForDate:[NSDate date]];
Community
  • 1
  • 1
Volker
  • 4,640
  • 1
  • 23
  • 31
  • 1
    See the answer at http://stackoverflow.com/questions/14592556/objective-c-how-can-i-get-the-current-date-in-utc-timezone as well. – ahwulf Feb 27 '14 at 14:05
7

Swift Solution

Use timeIntervalSince1970 to get UTC timestamp.

let secondsSince1970: TimeInterval = Date().timeIntervalSince1970

If you want to work with timezones, use DateFormatter.

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss z"

dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
print(dateFormatter.string(from: date))
// output: 2019-01-10 00:24:12 GMT

dateFormatter.timeZone = TimeZone(abbreviation: "America/Los_Angeles")
print(dateFormatter.string(from: date)) 
// output: 2019-01-09 16:24:12 PST
Derek Soike
  • 11,238
  • 3
  • 79
  • 74
6

Just timeIntervalSince1970 returns UTC time as a double (NSTimeInterval)

To get a 32 bit representation (maybe for interaction with embedded systems):

time_t timestamp = (time_t)[[NSDate date] timeIntervalSince1970];

Angelo
  • 173
  • 2
  • 4
  • 13