VansFannel VansFannel - 3 months ago 15
iOS Question

Get [NSDate date] with UTC time

I'm developing an iOS 5.0+ app with latest SDK.

I have this code to get a date as string:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"ddMMyyyy HH:mm"];
NSDate* now = [NSDate date];
NSString* dateAsString = [formatter stringFromDate:now];


var
now
is
2013-11-20 10:59:21 CET
and
dateAsString
is
20112013 10:59
but I need to get this date with UTC time. Here in Spain, I think is -1 hour.

How can I get [NSDate date] with UTC time?

Answer

Use NSTimeZone:

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"ddMMyyyy HH:mm"];

// Add this part to your code
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];

NSDate *now = [NSDate date];
NSString *dateAsString = [formatter stringFromDate:now];
Comments