tags:

views:

1449

answers:

5
+4  Q: 

GMT time on iPhone

How do I get GMT time?

NSDate *c =[NSDate date];

gives system time, not GMT.

A: 

NSDate stores the time zone internally -- there are a few functions you can call and pass in a target timezone if you jsut want a string representation of the date, see apple's documentation

olliej
A: 

See:

CFTimeZoneCreateWithTimeIntervalFromGMT secondsFromGMT

Date & Time Programming Guide

mahboudz
+4  A: 
- (NSDate*) convertToUTC:(NSDate*)sourceDate
{
    NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
    NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];

    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset;

    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:sourceDate] autorelease]; 
    return destinationDate;
}
Ramin
+3  A: 

If it's for display purposes you want to display it, use NSDateFormatter like so:

NSDate *myDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

// Set date style:
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];

NSString *GMTDateString = [dateFormatter stringFromDate: myDate];
Barry Hurley
+3  A: 

This is a simpler version of Ramin's answer

+ (NSDate *) GMTNow
{ 
 NSDate *sourceDate = [NSDate date];
    NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone];
    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMT];

    [sourceDate addTimeInterval:currentGMTOffset];

    return sourceDate;
}
Chris Beeson