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?
Solved I can use [[NSDate date] timeIntervalSince1970];
:)
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]];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With