Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS get UTC timestamp

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

like image 299
AYMADA Avatar asked Feb 27 '14 13:02

AYMADA


2 Answers

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]];
like image 91
Volker Avatar answered Sep 24 '22 02:09

Volker


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
like image 39
Derek Soike Avatar answered Sep 23 '22 02:09

Derek Soike