Friday, May 3, 2013

NSTimeZone secondsFromGMTForDate example ios


secondsFromGMTForDate:

Returns the difference in seconds between the receiver and Greenwich Mean Time at a given date.
- (NSInteger)secondsFromGMTForDate:(NSDate *)aDate
Parameters
aDate
The date against which to test the receiver.
Return Value of [NSTimeZone secondsFromGMTForDate]
The difference in seconds between the receiver and Greenwich Mean Time at aDate.
Discussion
The difference may be different from the current difference if the time zone changes its offset from GMT at different points in the year—for example, the U.S. time zones change with daylight savings time.

Example of [NSTimeZone secondsFromGMTForDate]
- (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;
}
Example of [NSTimeZone secondsFromGMTForDate]
NSDate *sourceDate = [NSDate dateWithTimeIntervalSinceNow:3600 * 24 * 60];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
int timeZoneOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate] / 3600;
NSLog(@"sourceDate=%@ timeZoneOffset=%d", sourceDate, timeZoneOffset);