The accepted answer by Alex Wien is incorrect.
By default, NSDateFormatter adjusts the NSDate’s date-time value from UTC to the user's local time zone. To prevent that adjustment, tell the NSDateFormatter to use the time zone for UTC
.
To verify results, google "current time utc".
My source code below should do the job, meaning get the current date-time as a string in ISO 8601 format in the UTC (Zulu) time zone signified by a Z
on the end.
NSDate* datetime = [NSDate date];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; // Prevent adjustment to user's local time zone.
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString* dateTimeInIsoFormatForZuluTimeZone = [dateFormatter stringFromDate:datetime];
You could put this logic in a pair of convenience methods somewhere in your app.
- (NSString*)now
{
// Purpose: Return a string of the current date-time in UTC (Zulu) time zone in ISO 8601 format.
return [self toStringFromDateTime:[NSDate date]];
}
…and…
- (NSString*)toStringFromDateTime:(NSDate*)datetime
{
// Purpose: Return a string of the specified date-time in UTC (Zulu) time zone in ISO 8601 format.
// Example: 2013-10-25T06:59:43.431Z
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString* dateTimeInIsoFormatForZuluTimeZone = [dateFormatter stringFromDate:datetime];
return dateTimeInIsoFormatForZuluTimeZone;
}
Example of usage…
NSString* now = [self now];
Or turn those minus signs into plus signs to use as class methods rather than instance methods…
NSString* now = [SomeClassNameHere now];
Tip: For better readability by humans, change that T
in the format to a SPACE. For better interoperability by software, keep the T
. The ISO 8601 spec tolerates a space but recommends keeping the T
.
Tip: I've not tested, but… Some people say instantiating [NSDateFormatter][4]
is expensive. If doing so often (such as in a loop) consider caching a single instance for re-use.