iOS get UTC timestamp

18,184

Solution 1

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]];

Solution 2

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

Solution 3

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];

Share:
18,184
AYMADA
Author by

AYMADA

Updated on June 04, 2022

Comments

  • AYMADA
    AYMADA almost 2 years

    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]; :)

  • ahwulf
    ahwulf about 10 years
    See the answer at stackoverflow.com/questions/14592556/… as well.