3

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?

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • I didn't but plz look into timezone and locale – Anoop Vaidya Nov 20 '13 at 10:05
  • 1
    You *have* UTC time in the NSDate object. If you bothered to search at all you'd find that NSDateFormatter assumes the local timezone unless you set it to UTC. – Hot Licks Nov 20 '13 at 13:01
  • 1
    It's always hard to find a duplicate when you want to, but this question comes up weekly; daily at certain times of the year. – Hot Licks Nov 20 '13 at 13:05

2 Answers2

19

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

You can add timezone with your date formatter as

NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];
manujmv
  • 6,450
  • 1
  • 22
  • 35